From 8f6127160666d6c2688a145a8ffdaed3f0cca65b Mon Sep 17 00:00:00 2001
From: gnembon <41132274+gnembon@users.noreply.github.com>
Date: Sat, 4 Feb 2023 13:26:21 +0100
Subject: [PATCH] semi-auto cleanup
---
.../java/carpet/script/CarpetContext.java | 10 +-
.../java/carpet/script/CarpetEventServer.java | 845 +++++---
.../java/carpet/script/CarpetExpression.java | 74 +-
.../java/carpet/script/CarpetScriptHost.java | 725 ++++---
.../carpet/script/CarpetScriptServer.java | 276 ++-
src/main/java/carpet/script/Context.java | 75 +-
.../java/carpet/script/EntityEventsGroup.java | 97 +-
src/main/java/carpet/script/Expression.java | 851 ++++----
src/main/java/carpet/script/Fluff.java | 136 +-
src/main/java/carpet/script/LazyValue.java | 26 +-
src/main/java/carpet/script/Module.java | 98 +-
src/main/java/carpet/script/ScriptHost.java | 317 +--
src/main/java/carpet/script/ScriptServer.java | 3 +-
src/main/java/carpet/script/Tokenizer.java | 162 +-
.../script/annotation/AnnotationParser.java | 88 +-
.../script/annotation/ListConverter.java | 28 +-
.../carpet/script/annotation/Locator.java | 82 +-
.../script/annotation/MapConverter.java | 51 +-
.../script/annotation/OptionalConverter.java | 22 +-
.../script/annotation/OutputConverter.java | 18 +-
.../java/carpet/script/annotation/Param.java | 46 +-
.../script/annotation/ScarpetFunction.java | 2 +-
.../annotation/SimpleTypeConverter.java | 13 +-
.../carpet/script/annotation/ValueCaster.java | 13 +-
.../script/annotation/ValueConverter.java | 41 +-
.../java/carpet/script/api/Auxiliary.java | 929 +++++----
.../carpet/script/api/BlockIterators.java | 275 +--
src/main/java/carpet/script/api/Entities.java | 274 +--
.../java/carpet/script/api/Inventories.java | 450 +++--
.../java/carpet/script/api/Monitoring.java | 50 +-
.../java/carpet/script/api/Scoreboards.java | 764 ++++---
.../java/carpet/script/api/Threading.java | 39 +-
.../java/carpet/script/api/WorldAccess.java | 1380 +++++++------
.../java/carpet/script/argument/Argument.java | 1 +
.../carpet/script/argument/BlockArgument.java | 46 +-
.../carpet/script/argument/FileArgument.java | 495 +++--
.../script/argument/FunctionArgument.java | 80 +-
.../script/argument/Vector3Argument.java | 39 +-
.../script/command/CommandArgument.java | 593 ++++--
.../carpet/script/command/CommandToken.java | 82 +-
.../script/exception/BreakStatement.java | 2 +-
.../exception/CarpetExpressionException.java | 11 +-
.../script/exception/ContinueStatement.java | 2 +-
.../script/exception/ExitStatement.java | 3 +-
.../script/exception/ExpressionException.java | 32 +-
.../script/exception/IntegrityException.java | 2 +-
.../InternalExpressionException.java | 18 +-
.../script/exception/LoadException.java | 14 +-
.../exception/ProcessedThrowStatement.java | 10 +-
.../script/exception/ReturnStatement.java | 3 +-
.../exception/StacklessRuntimeException.java | 12 +-
.../script/exception/ThrowStatement.java | 21 +-
.../carpet/script/exception/Throwables.java | 61 +-
.../carpet/script/language/Arithmetic.java | 115 +-
.../carpet/script/language/ControlFlow.java | 88 +-
.../script/language/DataStructures.java | 276 +--
.../carpet/script/language/Functions.java | 70 +-
.../java/carpet/script/language/Loops.java | 348 ++--
.../carpet/script/language/Operators.java | 467 +++--
src/main/java/carpet/script/language/Sys.java | 243 ++-
.../carpet/script/language/Threading.java | 57 +-
.../carpet/script/utils/AppStoreManager.java | 277 ++-
.../java/carpet/script/utils/BiomeInfo.java | 17 +-
.../script/utils/EquipmentInventory.java | 45 +-
.../java/carpet/script/utils/GlocalFlag.java | 18 +-
.../carpet/script/utils/InputValidator.java | 16 +-
.../script/utils/PerlinNoiseSampler.java | 191 +-
.../script/utils/ScarpetJsonDeserializer.java | 35 +-
.../carpet/script/utils/ShapeDispatcher.java | 1765 +++++++++++------
.../carpet/script/utils/ShapesRenderer.java | 908 +++++----
.../script/utils/SimplexNoiseSampler.java | 198 +-
.../script/utils/SnoopyCommandSource.java | 73 +-
.../java/carpet/script/utils/SystemInfo.java | 134 +-
.../java/carpet/script/utils/WorldTools.java | 72 +-
.../script/utils/shapes/ShapeDirection.java | 15 +-
.../script/value/AbstractListValue.java | 14 +-
.../java/carpet/script/value/BlockValue.java | 181 +-
.../carpet/script/value/BooleanValue.java | 32 +-
.../script/value/ContainerValueInterface.java | 6 +-
.../java/carpet/script/value/EntityValue.java | 1316 ++++++------
.../script/value/FormattedTextValue.java | 71 +-
.../carpet/script/value/FrameworkValue.java | 2 +-
.../script/value/FunctionAnnotationValue.java | 8 +-
.../script/value/FunctionSignatureValue.java | 12 +-
.../value/FunctionUnpackedArgumentsValue.java | 6 +-
.../carpet/script/value/FunctionValue.java | 152 +-
.../carpet/script/value/LContainerValue.java | 17 +-
.../carpet/script/value/LazyListValue.java | 87 +-
.../java/carpet/script/value/ListValue.java | 333 ++--
.../java/carpet/script/value/MapValue.java | 127 +-
.../script/value/NBTSerializableValue.java | 496 +++--
.../java/carpet/script/value/NullValue.java | 45 +-
.../carpet/script/value/NumericValue.java | 232 +--
.../java/carpet/script/value/ScreenValue.java | 420 ++--
.../java/carpet/script/value/StringValue.java | 17 +-
.../java/carpet/script/value/ThreadValue.java | 72 +-
.../java/carpet/script/value/UndefValue.java | 80 +-
src/main/java/carpet/script/value/Value.java | 165 +-
.../carpet/script/value/ValueConversions.java | 364 ++--
99 files changed, 11463 insertions(+), 8007 deletions(-)
diff --git a/src/main/java/carpet/script/CarpetContext.java b/src/main/java/carpet/script/CarpetContext.java
index cfb21eff..0455c1c5 100644
--- a/src/main/java/carpet/script/CarpetContext.java
+++ b/src/main/java/carpet/script/CarpetContext.java
@@ -18,11 +18,12 @@ public class CarpetContext extends Context
public CommandSourceStack s;
private final BlockPos origin;
- public CarpetContext(CarpetScriptHost host, CommandSourceStack source) {
+ public CarpetContext(final CarpetScriptHost host, final CommandSourceStack source)
+ {
this(host, source, BlockPos.ZERO);
}
- public CarpetContext(ScriptHost host, CommandSourceStack source, BlockPos origin)
+ public CarpetContext(final ScriptHost host, final CommandSourceStack source, final BlockPos origin)
{
super(host);
s = source;
@@ -59,7 +60,8 @@ public class CarpetContext extends Context
return s.getLevel().registryAccess();
}
- public Registry registry(ResourceKey extends Registry extends T>> resourceKey) {
+ public Registry registry(final ResourceKey extends Registry extends T>> resourceKey)
+ {
return registryAccess().registryOrThrow(resourceKey);
}
@@ -73,7 +75,7 @@ public class CarpetContext extends Context
return origin;
}
- public void swapSource(CommandSourceStack source)
+ public void swapSource(final CommandSourceStack source)
{
s = source;
}
diff --git a/src/main/java/carpet/script/CarpetEventServer.java b/src/main/java/carpet/script/CarpetEventServer.java
index 3c84663d..96a19877 100644
--- a/src/main/java/carpet/script/CarpetEventServer.java
+++ b/src/main/java/carpet/script/CarpetEventServer.java
@@ -22,6 +22,7 @@ import carpet.script.value.ValueConversions;
import carpet.utils.CarpetProfiler;
import carpet.utils.Messenger;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
+
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -40,6 +41,7 @@ import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
+
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
@@ -92,27 +94,31 @@ public class CarpetEventServer
public final FunctionValue function;
public final List parametrizedArgs;
- public Callback(String host, String target, FunctionValue function, List parametrizedArgs)
+ public Callback(final String host, final String target, final FunctionValue function, final List parametrizedArgs)
{
this.host = host;
this.function = function;
this.optionalTarget = target;
- this.parametrizedArgs = parametrizedArgs==null?NOARGS:parametrizedArgs;
+ this.parametrizedArgs = parametrizedArgs == null ? NOARGS : parametrizedArgs;
}
/**
* Used also in entity events
- * @param sender - entity command source
+ *
+ * @param sender - entity command source
* @param runtimeArgs = options
*/
- public CallbackResult execute(CommandSourceStack sender, List runtimeArgs)
+ public CallbackResult execute(final CommandSourceStack sender, List runtimeArgs)
{
if (!this.parametrizedArgs.isEmpty())
{
runtimeArgs = new ArrayList<>(runtimeArgs);
runtimeArgs.addAll(this.parametrizedArgs);
}
- if (CarpetServer.scriptServer == null) return CallbackResult.FAIL; // already stopped
+ if (CarpetServer.scriptServer == null)
+ {
+ return CallbackResult.FAIL; // already stopped
+ }
return CarpetServer.scriptServer.events.runEventCall(
sender.withPermission(CarpetSettings.runPermissionLevel),
host, optionalTarget, function, runtimeArgs);
@@ -120,31 +126,33 @@ public class CarpetEventServer
/**
* Used also in entity events
- * @param sender - sender of the signal
+ *
+ * @param sender - sender of the signal
* @param optionalRecipient - optional target player argument
- * @param runtimeArgs = options
+ * @param runtimeArgs = options
*/
- public CallbackResult signal(CommandSourceStack sender, ServerPlayer optionalRecipient, List runtimeArgs)
+ public CallbackResult signal(final CommandSourceStack sender, final ServerPlayer optionalRecipient, final List runtimeArgs)
{
// recipent of the call doesn't match the handlingHost
- if (optionalRecipient != null && !optionalRecipient.getScoreboardName().equals(optionalTarget))
- return CallbackResult.FAIL;
- return execute(sender, runtimeArgs);
+ return optionalRecipient != null && !optionalRecipient.getScoreboardName().equals(optionalTarget) ? CallbackResult.FAIL : execute(sender, runtimeArgs);
}
@Override
public String toString()
{
- return function.getString()+((host==null)?"":"(from "+host+(optionalTarget == null?"":"/"+optionalTarget)+")");
+ return function.getString() + ((host == null) ? "" : "(from " + host + (optionalTarget == null ? "" : "/" + optionalTarget) + ")");
}
- public static record Signature(String function, String host, String target) {}
-
- public static Signature fromString(String str)
+
+ public record Signature(String function, String host, String target)
{
- Pattern find = Pattern.compile("(\\w+)(?:\\(from (\\w+)(?:/(\\w+))?\\))?");
- Matcher matcher = find.matcher(str);
- if(matcher.matches())
+ }
+
+ public static Signature fromString(final String str)
+ {
+ final Pattern find = Pattern.compile("(\\w+)(?:\\(from (\\w+)(?:/(\\w+))?\\))?");
+ final Matcher matcher = find.matcher(str);
+ if (matcher.matches())
{
return new Signature(matcher.group(1), matcher.group(2), matcher.group(3));
}
@@ -158,7 +166,7 @@ public class CarpetEventServer
private final CarpetContext ctx;
public long dueTime;
- public ScheduledCall(CarpetContext context, FunctionValue function, List args, long dueTime)
+ public ScheduledCall(final CarpetContext context, final FunctionValue function, final List args, final long dueTime)
{
// ignoring target as we will be always calling self
super(context.host.getName(), null, function, args);
@@ -186,7 +194,7 @@ public class CarpetEventServer
final boolean isSystem;
final boolean perPlayerDistribution;
- public CallbackList(int reqArgs, boolean isSystem, boolean isGlobalOnly)
+ public CallbackList(final int reqArgs, final boolean isSystem, final boolean isGlobalOnly)
{
this.callList = new ArrayList<>();
this.removedCalls = new ArrayList<>();
@@ -202,7 +210,7 @@ public class CarpetEventServer
return new ArrayList<>(callList);
}
- private void removeCallsIf(Predicate when)
+ private void removeCallsIf(final Predicate when)
{
if (!inCall && !inSignal)
{
@@ -212,34 +220,38 @@ public class CarpetEventServer
// we are ok with list growing in the meantime and parallel access, we are only scanning.
for (int i = 0; i < callList.size(); i++)
{
- Callback call = callList.get(i);
- if (when.test(call)) removedCalls.add(call);
+ final Callback call = callList.get(i);
+ if (when.test(call))
+ {
+ removedCalls.add(call);
+ }
}
}
/**
* Handles only built-in events from the events system
+ *
* @param argumentSupplier
* @param cmdSourceSupplier
* @return Whether this event call has been cancelled
*/
- public boolean call(Supplier> argumentSupplier, Supplier cmdSourceSupplier)
+ public boolean call(final Supplier> argumentSupplier, final Supplier cmdSourceSupplier)
{
- if (callList.size() > 0 && CarpetServer.scriptServer != null)
+ if (!callList.isEmpty() && CarpetServer.scriptServer != null)
{
- Boolean isCancelled = CarpetServer.scriptServer.events.handleEvents.runIfEnabled( () -> {
- CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet events", CarpetProfiler.TYPE.GENERAL);
- List argv = argumentSupplier.get(); // empty for onTickDone
- CommandSourceStack source;
+ final Boolean isCancelled = CarpetServer.scriptServer.events.handleEvents.runIfEnabled(() -> {
+ final CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet events", CarpetProfiler.TYPE.GENERAL);
+ final List argv = argumentSupplier.get(); // empty for onTickDone
+ final CommandSourceStack source;
try
{
source = cmdSourceSupplier.get();
}
- catch (NullPointerException noReference) // todo figure out what happens when closing.
+ catch (final NullPointerException noReference) // todo figure out what happens when closing.
{
return false;
}
- String nameCheck = perPlayerDistribution ? source.getTextName() : null;
+ final String nameCheck = perPlayerDistribution ? source.getTextName() : null;
assert argv.size() == reqArgs;
boolean cancelled = false;
try
@@ -249,23 +261,33 @@ public class CarpetEventServer
inCall = true;
for (int i = 0; i < callList.size(); i++)
{
- Callback call = callList.get(i);
+ final Callback call = callList.get(i);
// supressing calls where target player hosts simply don't match
// handling global hosts with player targets is left to when the host is resolved (few calls deeper).
- if (nameCheck != null && call.optionalTarget != null && !nameCheck.equals(call.optionalTarget)) continue;
- CallbackResult result = call.execute(source, argv);
- if(result == CallbackResult.CANCEL) {
+ if (nameCheck != null && call.optionalTarget != null && !nameCheck.equals(call.optionalTarget))
+ {
+ continue;
+ }
+ final CallbackResult result = call.execute(source, argv);
+ if (result == CallbackResult.CANCEL)
+ {
cancelled = true;
break;
}
- if (result == CallbackResult.FAIL) removedCalls.add(call);
+ if (result == CallbackResult.FAIL)
+ {
+ removedCalls.add(call);
+ }
}
}
finally
{
inCall = false;
}
- for (Callback call : removedCalls) callList.remove(call);
+ for (final Callback call : removedCalls)
+ {
+ callList.remove(call);
+ }
removedCalls.clear();
CarpetProfiler.end_current_section(currentSection);
return cancelled;
@@ -275,9 +297,12 @@ public class CarpetEventServer
return false;
}
- public int signal(CommandSourceStack sender, ServerPlayer optinoalReceipient, List callArg)
+ public int signal(final CommandSourceStack sender, final ServerPlayer optinoalReceipient, final List callArg)
{
- if (callList.isEmpty()) return 0;
+ if (callList.isEmpty())
+ {
+ return 0;
+ }
int successes = 0;
try
{
@@ -285,7 +310,10 @@ public class CarpetEventServer
for (int i = 0; i < callList.size(); i++)
{
// skipping tracking of fails, its explicit call
- if (callList.get(i).signal(sender, optinoalReceipient, callArg) == CallbackResult.SUCCESS) successes++;
+ if (callList.get(i).signal(sender, optinoalReceipient, callArg) == CallbackResult.SUCCESS)
+ {
+ successes++;
+ }
}
}
finally
@@ -295,21 +323,21 @@ public class CarpetEventServer
return successes;
}
- public boolean addFromExternal(CommandSourceStack source, String hostName, String funName, Consumer hostOnEventHandler)
+ public boolean addFromExternal(final CommandSourceStack source, final String hostName, final String funName, final Consumer hostOnEventHandler)
{
- ScriptHost host = CarpetServer.scriptServer.getAppHostByName(hostName);
+ final ScriptHost host = CarpetServer.scriptServer.getAppHostByName(hostName);
if (host == null)
{
// impossible call to add
- Messenger.m(source, "r Unknown app "+hostName);
+ Messenger.m(source, "r Unknown app " + hostName);
return false;
}
hostOnEventHandler.accept(host);
- FunctionValue udf = host.getFunction(funName);
+ final FunctionValue udf = host.getFunction(funName);
if (udf == null || udf.getArguments().size() != reqArgs)
{
// call won't match arguments
- Messenger.m(source, "r Callback doesn't expect required number of arguments: "+reqArgs);
+ Messenger.m(source, "r Callback doesn't expect required number of arguments: " + reqArgs);
return false;
}
String target = null;
@@ -319,7 +347,7 @@ public class CarpetEventServer
{
target = source.getPlayerOrException().getScoreboardName();
}
- catch (CommandSyntaxException e)
+ catch (final CommandSyntaxException e)
{
Messenger.m(source, "r Cannot add event to a player scoped app from a command without a player context");
return false;
@@ -332,7 +360,8 @@ public class CarpetEventServer
callList.add(new Callback(hostName, target, udf, null));
return true;
}
- public boolean addEventCallInternal(ScriptHost host, FunctionValue function, List args)
+
+ public boolean addEventCallInternal(final ScriptHost host, final FunctionValue function, final List args)
{
if (function == null || (function.getArguments().size() - args.size()) != reqArgs)
{
@@ -344,27 +373,27 @@ public class CarpetEventServer
return true;
}
- public void removeEventCall(String hostName, String target, String funName)
+ public void removeEventCall(final String hostName, final String target, final String funName)
{
- removeCallsIf((c)-> c.function.getString().equals(funName)
+ removeCallsIf((c) -> c.function.getString().equals(funName)
&& (Objects.equals(c.host, hostName))
&& (Objects.equals(c.optionalTarget, target))
);
}
- public void removeAllCalls(CarpetScriptHost host)
+ public void removeAllCalls(final CarpetScriptHost host)
{
- removeCallsIf((c)-> (Objects.equals(c.host, host.getName()))
+ removeCallsIf((c) -> (Objects.equals(c.host, host.getName()))
&& (Objects.equals(c.optionalTarget, host.user)));
}
- public void createChildEvents(CarpetScriptHost host)
+ public void createChildEvents(final CarpetScriptHost host)
{
- List copyCalls = new ArrayList<>();
- callList.forEach((c)->
+ final List copyCalls = new ArrayList<>();
+ callList.forEach((c) ->
{
if ((Objects.equals(c.host, host.getName()))
- && c.optionalTarget == null)
+ && c.optionalTarget == null)
{
copyCalls.add(new Callback(c.host, host.user, c.function, c.parametrizedArgs));
}
@@ -375,11 +404,15 @@ public class CarpetEventServer
public void clearEverything()
{
// when some moron puts /reload in an event call.
- if (inSignal || inCall) callList = new ArrayList<>();
+ if (inSignal || inCall)
+ {
+ callList = new ArrayList<>();
+ }
callList.clear();
}
- public void sortByPriority(CarpetScriptServer scriptServer) {
+ public void sortByPriority(final CarpetScriptServer scriptServer)
+ {
callList.sort(Comparator.comparingDouble(c -> -scriptServer.getAppHostByName(c.host).eventPriority));
}
}
@@ -387,10 +420,14 @@ public class CarpetEventServer
public static class Event
{
public static final Map byName = new HashMap<>();
- public static List publicEvents(CarpetScriptServer server)
+
+ public static List publicEvents(final CarpetScriptServer server)
{
- List events = byName.values().stream().filter(e -> e.isPublic).collect(Collectors.toList());
- if (server != null) events.addAll(server.events.customEvents.values());
+ final List events = byName.values().stream().filter(e -> e.isPublic).collect(Collectors.toList());
+ if (server != null)
+ {
+ events.addAll(server.events.customEvents.values());
+ }
return events;
}
@@ -453,6 +490,7 @@ public class CarpetEventServer
{
return true;
}
+
@Override
public void onTick()
{
@@ -465,24 +503,22 @@ public class CarpetEventServer
public static final Event CHUNK_GENERATED = new Event("chunk_generated", 2, true)
{
@Override
- public void onChunkEvent(ServerLevel world, ChunkPos chPos, boolean generated)
+ public void onChunkEvent(final ServerLevel world, final ChunkPos chPos, final boolean generated)
{
- handler.call( () ->
- {
- return Arrays.asList(new NumericValue(chPos.x << 4), new NumericValue(chPos.z << 4));
- }, () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world)
+ handler.call(
+ () -> Arrays.asList(new NumericValue(chPos.x << 4), new NumericValue(chPos.z << 4)),
+ () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world)
);
}
};
public static final Event CHUNK_LOADED = new Event("chunk_loaded", 2, true)
{
@Override
- public void onChunkEvent(ServerLevel world, ChunkPos chPos, boolean generated)
+ public void onChunkEvent(final ServerLevel world, final ChunkPos chPos, final boolean generated)
{
- handler.call( () ->
- {
- return Arrays.asList(new NumericValue(chPos.x << 4), new NumericValue(chPos.z << 4));
- }, () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world)
+ handler.call(
+ () -> Arrays.asList(new NumericValue(chPos.x << 4), new NumericValue(chPos.z << 4)),
+ () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world)
);
}
};
@@ -490,7 +526,7 @@ public class CarpetEventServer
public static final Event CHUNK_UNLOADED = new Event("chunk_unloaded", 2, true)
{
@Override
- public void onChunkEvent(ServerLevel world, ChunkPos chPos, boolean generated)
+ public void onChunkEvent(final ServerLevel world, final ChunkPos chPos, final boolean generated)
{
handler.call(
() -> Arrays.asList(new NumericValue(chPos.x << 4), new NumericValue(chPos.z << 4)),
@@ -502,45 +538,45 @@ public class CarpetEventServer
public static final Event PLAYER_JUMPS = new Event("player_jumps", 1, false)
{
@Override
- public boolean onPlayerEvent(ServerPlayer player)
+ public boolean onPlayerEvent(final ServerPlayer player)
{
- handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
+ handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
return false;
}
};
public static final Event PLAYER_DEPLOYS_ELYTRA = new Event("player_deploys_elytra", 1, false)
{
@Override
- public boolean onPlayerEvent(ServerPlayer player)
+ public boolean onPlayerEvent(final ServerPlayer player)
{
- handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
+ handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
return false;
}
};
public static final Event PLAYER_WAKES_UP = new Event("player_wakes_up", 1, false)
{
@Override
- public boolean onPlayerEvent(ServerPlayer player)
+ public boolean onPlayerEvent(final ServerPlayer player)
{
- handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
+ handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
return false;
}
};
public static final Event PLAYER_ESCAPES_SLEEP = new Event("player_escapes_sleep", 1, false)
{
@Override
- public boolean onPlayerEvent(ServerPlayer player)
+ public boolean onPlayerEvent(final ServerPlayer player)
{
- handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
+ handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
return false;
}
};
public static final Event PLAYER_RIDES = new Event("player_rides", 5, false)
{
@Override
- public void onMountControls(ServerPlayer player, float strafeSpeed, float forwardSpeed, boolean jumping, boolean sneaking)
+ public void onMountControls(final ServerPlayer player, final float strafeSpeed, final float forwardSpeed, final boolean jumping, final boolean sneaking)
{
- handler.call( () -> Arrays.asList(new EntityValue(player),
+ handler.call(() -> Arrays.asList(new EntityValue(player),
new NumericValue(forwardSpeed), new NumericValue(strafeSpeed), BooleanValue.of(jumping), BooleanValue.of(sneaking)
), player::createCommandSourceStack);
}
@@ -548,45 +584,40 @@ public class CarpetEventServer
public static final Event PLAYER_USES_ITEM = new Event("player_uses_item", 3, false)
{
@Override
- public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack)
+ public boolean onItemAction(final ServerPlayer player, final InteractionHand enumhand, final ItemStack itemstack)
{
- return handler.call( () ->
- {
- //ItemStack itemstack = player.getStackInHand(enumhand);
- return Arrays.asList(
- new EntityValue(player),
- ValueConversions.of(itemstack, player.getLevel().registryAccess()),
- StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand")
- );
- }, player::createCommandSourceStack);
+ return handler.call(() ->
+ Arrays.asList(
+ new EntityValue(player),
+ ValueConversions.of(itemstack, player.getLevel().registryAccess()),
+ StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand")
+ ), player::createCommandSourceStack);
}
};
public static final Event PLAYER_CLICKS_BLOCK = new Event("player_clicks_block", 3, false)
{
@Override
- public boolean onBlockAction(ServerPlayer player, BlockPos blockpos, Direction facing)
+ public boolean onBlockAction(final ServerPlayer player, final BlockPos blockpos, final Direction facing)
{
- return handler.call( () ->
- {
- return Arrays.asList(
- new EntityValue(player),
- new BlockValue(null, player.getLevel(), blockpos),
- StringValue.of(facing.getName())
- );
- }, player::createCommandSourceStack);
+ return handler.call(() ->
+ Arrays.asList(
+ new EntityValue(player),
+ new BlockValue(null, player.getLevel(), blockpos),
+ StringValue.of(facing.getName())
+ ), player::createCommandSourceStack);
}
};
public static final Event PLAYER_RIGHT_CLICKS_BLOCK = new Event("player_right_clicks_block", 6, false)
{
@Override
- public boolean onBlockHit(ServerPlayer player, InteractionHand enumhand, BlockHitResult hitRes)//ItemStack itemstack, Hand enumhand, BlockPos blockpos, Direction enumfacing, Vec3d vec3d)
+ public boolean onBlockHit(final ServerPlayer player, final InteractionHand enumhand, final BlockHitResult hitRes)
{
- return handler.call( () ->
+ return handler.call(() ->
{
- ItemStack itemstack = player.getItemInHand(enumhand);
- BlockPos blockpos = hitRes.getBlockPos();
- Direction enumfacing = hitRes.getDirection();
- Vec3 vec3d = hitRes.getLocation().subtract(blockpos.getX(), blockpos.getY(), blockpos.getZ());
+ final ItemStack itemstack = player.getItemInHand(enumhand);
+ final BlockPos blockpos = hitRes.getBlockPos();
+ final Direction enumfacing = hitRes.getDirection();
+ final Vec3 vec3d = hitRes.getLocation().subtract(blockpos.getX(), blockpos.getY(), blockpos.getZ());
return Arrays.asList(
new EntityValue(player),
ValueConversions.of(itemstack, player.getLevel().registryAccess()),
@@ -605,13 +636,13 @@ public class CarpetEventServer
public static final Event PLAYER_INTERACTS_WITH_BLOCK = new Event("player_interacts_with_block", 5, false)
{
@Override
- public boolean onBlockHit(ServerPlayer player, InteractionHand enumhand, BlockHitResult hitRes)
+ public boolean onBlockHit(final ServerPlayer player, final InteractionHand enumhand, final BlockHitResult hitRes)
{
- handler.call( () ->
+ handler.call(() ->
{
- BlockPos blockpos = hitRes.getBlockPos();
- Direction enumfacing = hitRes.getDirection();
- Vec3 vec3d = hitRes.getLocation().subtract(blockpos.getX(), blockpos.getY(), blockpos.getZ());
+ final BlockPos blockpos = hitRes.getBlockPos();
+ final Direction enumfacing = hitRes.getDirection();
+ final Vec3 vec3d = hitRes.getLocation().subtract(blockpos.getX(), blockpos.getY(), blockpos.getZ());
return Arrays.asList(
new EntityValue(player),
StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand"),
@@ -630,9 +661,9 @@ public class CarpetEventServer
public static final Event PLAYER_PLACING_BLOCK = new Event("player_placing_block", 4, false)
{
@Override
- public boolean onBlockPlaced(ServerPlayer player, BlockPos pos, InteractionHand enumhand, ItemStack itemstack)
+ public boolean onBlockPlaced(final ServerPlayer player, final BlockPos pos, final InteractionHand enumhand, final ItemStack itemstack)
{
- return handler.call( () -> Arrays.asList(
+ return handler.call(() -> Arrays.asList(
new EntityValue(player),
ValueConversions.of(itemstack, player.getLevel().registryAccess()),
StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand"),
@@ -643,9 +674,9 @@ public class CarpetEventServer
public static final Event PLAYER_PLACES_BLOCK = new Event("player_places_block", 4, false)
{
@Override
- public boolean onBlockPlaced(ServerPlayer player, BlockPos pos, InteractionHand enumhand, ItemStack itemstack)
+ public boolean onBlockPlaced(final ServerPlayer player, final BlockPos pos, final InteractionHand enumhand, final ItemStack itemstack)
{
- handler.call( () -> Arrays.asList(
+ handler.call(() -> Arrays.asList(
new EntityValue(player),
ValueConversions.of(itemstack, player.getLevel().registryAccess()),
StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand"),
@@ -657,7 +688,7 @@ public class CarpetEventServer
public static final Event PLAYER_BREAK_BLOCK = new Event("player_breaks_block", 2, false)
{
@Override
- public boolean onBlockBroken(ServerPlayer player, BlockPos pos, BlockState previousBS)
+ public boolean onBlockBroken(final ServerPlayer player, final BlockPos pos, final BlockState previousBS)
{
return handler.call(
() -> Arrays.asList(new EntityValue(player), new BlockValue(previousBS, player.getLevel(), pos)),
@@ -668,22 +699,22 @@ public class CarpetEventServer
public static final Event PLAYER_INTERACTS_WITH_ENTITY = new Event("player_interacts_with_entity", 3, false)
{
@Override
- public boolean onEntityHandAction(ServerPlayer player, Entity entity, InteractionHand enumhand)
+ public boolean onEntityHandAction(final ServerPlayer player, final Entity entity, final InteractionHand enumhand)
{
- return handler.call( () -> Arrays.asList(
- new EntityValue(player), new EntityValue(entity), StringValue.of(enumhand==InteractionHand.MAIN_HAND?"mainhand":"offhand")
+ return handler.call(() -> Arrays.asList(
+ new EntityValue(player), new EntityValue(entity), StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand")
), player::createCommandSourceStack);
}
};
public static final Event PLAYER_TRADES = new Event("player_trades", 5, false)
{
@Override
- public void onTrade(ServerPlayer player, Merchant merchant, MerchantOffer tradeOffer)
+ public void onTrade(final ServerPlayer player, final Merchant merchant, final MerchantOffer tradeOffer)
{
final RegistryAccess regs = player.getLevel().registryAccess();
- handler.call( () -> Arrays.asList(
+ handler.call(() -> Arrays.asList(
new EntityValue(player),
- merchant instanceof AbstractVillager ? new EntityValue((AbstractVillager) merchant) : Value.NULL,
+ merchant instanceof final AbstractVillager villager? new EntityValue(villager) : Value.NULL,
ValueConversions.of(tradeOffer.getBaseCostA(), regs),
ValueConversions.of(tradeOffer.getCostB(), regs),
ValueConversions.of(tradeOffer.getResult(), regs)
@@ -693,8 +724,9 @@ public class CarpetEventServer
public static final Event PLAYER_PICKS_UP_ITEM = new Event("player_picks_up_item", 2, false)
{
@Override
- public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack) {
- handler.call( () -> Arrays.asList(new EntityValue(player), ValueConversions.of(itemstack, player.getLevel().registryAccess())), player::createCommandSourceStack);
+ public boolean onItemAction(final ServerPlayer player, final InteractionHand enumhand, final ItemStack itemstack)
+ {
+ handler.call(() -> Arrays.asList(new EntityValue(player), ValueConversions.of(itemstack, player.getLevel().registryAccess())), player::createCommandSourceStack);
return false;
}
};
@@ -702,44 +734,44 @@ public class CarpetEventServer
public static final Event PLAYER_ATTACKS_ENTITY = new Event("player_attacks_entity", 2, false)
{
@Override
- public boolean onEntityHandAction(ServerPlayer player, Entity entity, InteractionHand enumhand)
+ public boolean onEntityHandAction(final ServerPlayer player, final Entity entity, final InteractionHand enumhand)
{
- return handler.call( () -> Arrays.asList(new EntityValue(player), new EntityValue(entity)), player::createCommandSourceStack);
+ return handler.call(() -> Arrays.asList(new EntityValue(player), new EntityValue(entity)), player::createCommandSourceStack);
}
};
public static final Event PLAYER_STARTS_SNEAKING = new Event("player_starts_sneaking", 1, false)
{
@Override
- public boolean onPlayerEvent(ServerPlayer player)
+ public boolean onPlayerEvent(final ServerPlayer player)
{
- handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
+ handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
return false;
}
};
public static final Event PLAYER_STOPS_SNEAKING = new Event("player_stops_sneaking", 1, false)
{
@Override
- public boolean onPlayerEvent(ServerPlayer player)
+ public boolean onPlayerEvent(final ServerPlayer player)
{
- handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
+ handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
return false;
}
};
public static final Event PLAYER_STARTS_SPRINTING = new Event("player_starts_sprinting", 1, false)
{
@Override
- public boolean onPlayerEvent(ServerPlayer player)
+ public boolean onPlayerEvent(final ServerPlayer player)
{
- handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
+ handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
return false;
}
};
public static final Event PLAYER_STOPS_SPRINTING = new Event("player_stops_sprinting", 1, false)
{
@Override
- public boolean onPlayerEvent(ServerPlayer player)
+ public boolean onPlayerEvent(final ServerPlayer player)
{
- handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
+ handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
return false;
}
};
@@ -747,10 +779,10 @@ public class CarpetEventServer
public static final Event PLAYER_RELEASED_ITEM = new Event("player_releases_item", 3, false)
{
@Override
- public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack)
+ public boolean onItemAction(final ServerPlayer player, final InteractionHand enumhand, final ItemStack itemstack)
{
// this.getStackInHand(this.getActiveHand()), this.activeItemStack)
- handler.call( () ->
+ handler.call(() ->
Arrays.asList(
new EntityValue(player),
ValueConversions.of(itemstack, player.getLevel().registryAccess()),
@@ -762,10 +794,10 @@ public class CarpetEventServer
public static final Event PLAYER_FINISHED_USING_ITEM = new Event("player_finishes_using_item", 3, false)
{
@Override
- public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack)
+ public boolean onItemAction(final ServerPlayer player, final InteractionHand enumhand, final ItemStack itemstack)
{
// this.getStackInHand(this.getActiveHand()), this.activeItemStack)
- return handler.call( () ->
+ return handler.call(() ->
Arrays.asList(
new EntityValue(player),
ValueConversions.of(itemstack, player.getLevel().registryAccess()),
@@ -776,25 +808,25 @@ public class CarpetEventServer
public static final Event PLAYER_DROPS_ITEM = new Event("player_drops_item", 1, false)
{
@Override
- public boolean onPlayerEvent(ServerPlayer player)
+ public boolean onPlayerEvent(final ServerPlayer player)
{
- return handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
+ return handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
}
};
public static final Event PLAYER_DROPS_STACK = new Event("player_drops_stack", 1, false)
{
@Override
- public boolean onPlayerEvent(ServerPlayer player)
+ public boolean onPlayerEvent(final ServerPlayer player)
{
- return handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
+ return handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
}
};
public static final Event PLAYER_CHOOSES_RECIPE = new Event("player_chooses_recipe", 3, false)
{
@Override
- public boolean onRecipeSelected(ServerPlayer player, ResourceLocation recipe, boolean fullStack)
+ public boolean onRecipeSelected(final ServerPlayer player, final ResourceLocation recipe, final boolean fullStack)
{
- return handler.call( () ->
+ return handler.call(() ->
Arrays.asList(
new EntityValue(player),
StringValue.of(NBTSerializableValue.nameFromRegistryId(recipe)),
@@ -805,10 +837,13 @@ public class CarpetEventServer
public static final Event PLAYER_SWITCHES_SLOT = new Event("player_switches_slot", 3, false)
{
@Override
- public void onSlotSwitch(ServerPlayer player, int from, int to)
+ public void onSlotSwitch(final ServerPlayer player, final int from, final int to)
{
- if (from == to) return; // initial slot update
- handler.call( () ->
+ if (from == to)
+ {
+ return; // initial slot update
+ }
+ handler.call(() ->
Arrays.asList(
new EntityValue(player),
new NumericValue(from),
@@ -819,19 +854,19 @@ public class CarpetEventServer
public static final Event PLAYER_SWAPS_HANDS = new Event("player_swaps_hands", 1, false)
{
@Override
- public boolean onPlayerEvent(ServerPlayer player)
+ public boolean onPlayerEvent(final ServerPlayer player)
{
- return handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
+ return handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
}
};
public static final Event PLAYER_SWINGS_HAND = new Event("player_swings_hand", 2, false)
{
@Override
- public void onHandAction(ServerPlayer player, InteractionHand hand)
+ public void onHandAction(final ServerPlayer player, final InteractionHand hand)
{
- handler.call( () -> Arrays.asList(
- new EntityValue(player),
- StringValue.of(hand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand")
+ handler.call(() -> Arrays.asList(
+ new EntityValue(player),
+ StringValue.of(hand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand")
)
, player::createCommandSourceStack);
}
@@ -839,24 +874,24 @@ public class CarpetEventServer
public static final Event PLAYER_TAKES_DAMAGE = new Event("player_takes_damage", 4, false)
{
@Override
- public boolean onDamage(Entity target, float amount, DamageSource source)
+ public boolean onDamage(final Entity target, final float amount, final DamageSource source)
{
- return handler.call( () ->
+ return handler.call(() ->
Arrays.asList(
- new EntityValue(target),
- new NumericValue(amount),
- StringValue.of(source.getMsgId()),
- source.getEntity()==null?Value.NULL:new EntityValue(source.getEntity())
+ new EntityValue(target),
+ new NumericValue(amount),
+ StringValue.of(source.getMsgId()),
+ source.getEntity() == null ? Value.NULL : new EntityValue(source.getEntity())
), target::createCommandSourceStack);
}
};
public static final Event PLAYER_DEALS_DAMAGE = new Event("player_deals_damage", 3, false)
{
@Override
- public boolean onDamage(Entity target, float amount, DamageSource source)
+ public boolean onDamage(final Entity target, final float amount, final DamageSource source)
{
- return handler.call( () ->
- Arrays.asList(new EntityValue(source.getEntity()), new NumericValue(amount), new EntityValue(target)),
+ return handler.call(() ->
+ Arrays.asList(new EntityValue(source.getEntity()), new NumericValue(amount), new EntityValue(target)),
() -> source.getEntity().createCommandSourceStack()
);
}
@@ -864,8 +899,9 @@ public class CarpetEventServer
public static final Event PLAYER_COLLIDES_WITH_ENTITY = new Event("player_collides_with_entity", 2, false)
{
@Override
- public boolean onEntityHandAction(ServerPlayer player, Entity entity, InteractionHand enumhand) {
- handler.call( () -> Arrays.asList(new EntityValue(player), new EntityValue(entity)), player::createCommandSourceStack);
+ public boolean onEntityHandAction(final ServerPlayer player, final Entity entity, final InteractionHand enumhand)
+ {
+ handler.call(() -> Arrays.asList(new EntityValue(player), new EntityValue(entity)), player::createCommandSourceStack);
return false;
}
};
@@ -873,86 +909,96 @@ public class CarpetEventServer
public static final Event PLAYER_DIES = new Event("player_dies", 1, false)
{
@Override
- public boolean onPlayerEvent(ServerPlayer player)
+ public boolean onPlayerEvent(final ServerPlayer player)
{
- handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
+ handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
return false;
}
};
public static final Event PLAYER_RESPAWNS = new Event("player_respawns", 1, false)
{
@Override
- public boolean onPlayerEvent(ServerPlayer player)
+ public boolean onPlayerEvent(final ServerPlayer player)
{
- handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
+ handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
return false;
}
};
public static final Event PLAYER_CHANGES_DIMENSION = new Event("player_changes_dimension", 5, false)
{
@Override
- public void onDimensionChange(ServerPlayer player, Vec3 from, Vec3 to, ResourceKey fromDim, ResourceKey dimTo)
+ public void onDimensionChange(final ServerPlayer player, final Vec3 from, final Vec3 to, final ResourceKey fromDim, final ResourceKey dimTo)
{
// eligibility already checked in mixin
- Value fromValue = ListValue.fromTriple(from.x, from.y, from.z);
- Value toValue = (to == null)?Value.NULL:ListValue.fromTriple(to.x, to.y, to.z);
- Value fromDimStr = new StringValue(NBTSerializableValue.nameFromRegistryId(fromDim.location()));
- Value toDimStr = new StringValue(NBTSerializableValue.nameFromRegistryId(dimTo.location()));
+ final Value fromValue = ListValue.fromTriple(from.x, from.y, from.z);
+ final Value toValue = (to == null) ? Value.NULL : ListValue.fromTriple(to.x, to.y, to.z);
+ final Value fromDimStr = new StringValue(NBTSerializableValue.nameFromRegistryId(fromDim.location()));
+ final Value toDimStr = new StringValue(NBTSerializableValue.nameFromRegistryId(dimTo.location()));
- handler.call( () -> Arrays.asList(new EntityValue(player), fromValue, fromDimStr, toValue, toDimStr), player::createCommandSourceStack);
+ handler.call(() -> Arrays.asList(new EntityValue(player), fromValue, fromDimStr, toValue, toDimStr), player::createCommandSourceStack);
}
};
- public static final Event PLAYER_CONNECTS = new Event("player_connects", 1, false) {
+ public static final Event PLAYER_CONNECTS = new Event("player_connects", 1, false)
+ {
@Override
- public boolean onPlayerEvent(ServerPlayer player)
+ public boolean onPlayerEvent(final ServerPlayer player)
{
- handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
+ handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
return false;
}
};
- public static final Event PLAYER_DISCONNECTS = new Event("player_disconnects", 2, false) {
+ public static final Event PLAYER_DISCONNECTS = new Event("player_disconnects", 2, false)
+ {
@Override
- public boolean onPlayerMessage(ServerPlayer player, String message)
+ public boolean onPlayerMessage(final ServerPlayer player, final String message)
{
- handler.call( () -> Arrays.asList(new EntityValue(player), new StringValue(message)), player::createCommandSourceStack);
+ handler.call(() -> Arrays.asList(new EntityValue(player), new StringValue(message)), player::createCommandSourceStack);
return false;
}
};
- public static final Event PLAYER_MESSAGE = new Event("player_message", 2, false) {
+ public static final Event PLAYER_MESSAGE = new Event("player_message", 2, false)
+ {
@Override
- public boolean onPlayerMessage(ServerPlayer player, String message) {
- return handler.call( () -> Arrays.asList(new EntityValue(player), new StringValue(message)), player::createCommandSourceStack);
+ public boolean onPlayerMessage(final ServerPlayer player, final String message)
+ {
+ return handler.call(() -> Arrays.asList(new EntityValue(player), new StringValue(message)), player::createCommandSourceStack);
}
};
- public static final Event PLAYER_COMMAND = new Event("player_command", 2, false) {
+ public static final Event PLAYER_COMMAND = new Event("player_command", 2, false)
+ {
@Override
- public boolean onPlayerMessage(ServerPlayer player, String message) {
- return handler.call( () -> Arrays.asList(new EntityValue(player), new StringValue(message)), player::createCommandSourceStack);
+ public boolean onPlayerMessage(final ServerPlayer player, final String message)
+ {
+ return handler.call(() -> Arrays.asList(new EntityValue(player), new StringValue(message)), player::createCommandSourceStack);
}
};
public static final Event STATISTICS = new Event("statistic", 4, false)
{
- private ResourceLocation getStatId(Stat stat)
+ private ResourceLocation getStatId(final Stat stat)
{
return stat.getType().getRegistry().getKey(stat.getValue());
}
+
private final Set skippedStats = Set.of(
- Stats.TIME_SINCE_DEATH,
- Stats.TIME_SINCE_REST,
- //Stats.PLAY_ONE_MINUTE,
- Stats.PLAY_TIME,
- Stats.TOTAL_WORLD_TIME
+ Stats.TIME_SINCE_DEATH,
+ Stats.TIME_SINCE_REST,
+ Stats.PLAY_TIME,
+ Stats.TOTAL_WORLD_TIME
);
+
@Override
- public void onPlayerStatistic(ServerPlayer player, Stat> stat, int amount)
+ public void onPlayerStatistic(final ServerPlayer player, final Stat> stat, final int amount)
{
- ResourceLocation id = getStatId(stat);
- if (skippedStats.contains(id)) return;
+ final ResourceLocation id = getStatId(stat);
+ if (skippedStats.contains(id))
+ {
+ return;
+ }
final Registry> registry = player.getLevel().registryAccess().registryOrThrow(Registries.STAT_TYPE);
- handler.call( () -> Arrays.asList(
+ handler.call(() -> Arrays.asList(
new EntityValue(player),
StringValue.of(NBTSerializableValue.nameFromRegistryId(registry.getKey(stat.getType()))),
StringValue.of(NBTSerializableValue.nameFromRegistryId(id)),
@@ -963,12 +1009,12 @@ public class CarpetEventServer
public static final Event LIGHTNING = new Event("lightning", 2, true)
{
@Override
- public void onWorldEventFlag(ServerLevel world, BlockPos pos, int flag)
+ public void onWorldEventFlag(final ServerLevel world, final BlockPos pos, final int flag)
{
handler.call(
() -> Arrays.asList(
new BlockValue(null, world, pos),
- flag>0?Value.TRUE:Value.FALSE
+ flag > 0 ? Value.TRUE : Value.FALSE
), () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world)
);
}
@@ -976,31 +1022,49 @@ public class CarpetEventServer
public static final Event CARPET_RULE_CHANGES = new Event("carpet_rule_changes", 2, true)
{
@Override
- public void onCarpetRuleChanges(CarpetRule> rule, CommandSourceStack source)
+ public void onCarpetRuleChanges(final CarpetRule> rule, final CommandSourceStack source)
{
- String identifier = rule.settingsManager().identifier();
+ final String identifier = rule.settingsManager().identifier();
final String namespace;
- if (!identifier.equals("carpet"))
+ if (!identifier.equals("carpet"))
{
- namespace = identifier+":";
- } else { namespace = "";}
+ namespace = identifier + ":";
+ }
+ else
+ {
+ namespace = "";
+ }
handler.call(
() -> Arrays.asList(
- new StringValue(namespace+rule.name()),
+ new StringValue(namespace + rule.name()),
new StringValue(RuleHelper.toRuleString(rule.value()))
), () -> source
);
}
};
+
//copy of Explosion.getCausingEntity() #TRACK#
- private static LivingEntity getExplosionCausingEntity(Entity entity)
+ private static LivingEntity getExplosionCausingEntity(final Entity entity)
{
- if (entity == null) return null;
- else if (entity instanceof PrimedTnt) return ((PrimedTnt)entity).getOwner();
- else if (entity instanceof LivingEntity) return (LivingEntity)entity;
- else if (entity instanceof Projectile) {
- Entity owner = ((Projectile)entity).getOwner();
- if (owner instanceof LivingEntity) return (LivingEntity)owner;
+ if (entity == null)
+ {
+ return null;
+ }
+ else if (entity instanceof final PrimedTnt tnt)
+ {
+ return tnt.getOwner();
+ }
+ else if (entity instanceof final LivingEntity le)
+ {
+ return le;
+ }
+ else if (entity instanceof final Projectile p)
+ {
+ final Entity owner = p.getOwner();
+ if (owner instanceof final LivingEntity le)
+ {
+ return le;
+ }
}
return null;
}
@@ -1008,18 +1072,18 @@ public class CarpetEventServer
public static final Event EXPLOSION_OUTCOME = new Event("explosion_outcome", 8, true)
{
@Override
- public void onExplosion(ServerLevel world, Entity e, Supplier attacker, double x, double y, double z, float power, boolean createFire, List affectedBlocks, List affectedEntities, Explosion.BlockInteraction type)
+ public void onExplosion(final ServerLevel world, final Entity e, final Supplier attacker, final double x, final double y, final double z, final float power, final boolean createFire, final List affectedBlocks, final List affectedEntities, final Explosion.BlockInteraction type)
{
handler.call(
() -> Arrays.asList(
ListValue.fromTriple(x, y, z),
NumericValue.of(power),
EntityValue.of(e),
- EntityValue.of(attacker!= null?attacker.get():Event.getExplosionCausingEntity(e)),
+ EntityValue.of(attacker != null ? attacker.get() : Event.getExplosionCausingEntity(e)),
StringValue.of(type.name().toLowerCase(Locale.ROOT)),
BooleanValue.of(createFire),
- ListValue.wrap(affectedBlocks.stream().filter(b -> !world.isEmptyBlock(b)). map( // da heck they send air blocks
- b -> new BlockValue(world.getBlockState(b),world,b)
+ ListValue.wrap(affectedBlocks.stream().filter(b -> !world.isEmptyBlock(b)).map( // da heck they send air blocks
+ b -> new BlockValue(world.getBlockState(b), world, b)
)),
ListValue.wrap(affectedEntities.stream().map(EntityValue::of))
), () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world)
@@ -1031,14 +1095,14 @@ public class CarpetEventServer
public static final Event EXPLOSION = new Event("explosion", 6, true)
{
@Override
- public void onExplosion(ServerLevel world, Entity e, Supplier attacker, double x, double y, double z, float power, boolean createFire, List affectedBlocks, List affectedEntities, Explosion.BlockInteraction type)
+ public void onExplosion(final ServerLevel world, final Entity e, final Supplier attacker, final double x, final double y, final double z, final float power, final boolean createFire, final List affectedBlocks, final List affectedEntities, final Explosion.BlockInteraction type)
{
handler.call(
() -> Arrays.asList(
ListValue.fromTriple(x, y, z),
NumericValue.of(power),
EntityValue.of(e),
- EntityValue.of(attacker!= null?attacker.get():Event.getExplosionCausingEntity(e)),
+ EntityValue.of(attacker != null ? attacker.get() : Event.getExplosionCausingEntity(e)),
StringValue.of(type.name().toLowerCase(Locale.ROOT)),
BooleanValue.of(createFire)
), () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world)
@@ -1047,7 +1111,7 @@ public class CarpetEventServer
};
@Deprecated
- public static String getEntityLoadEventName(EntityType extends Entity> et)
+ public static String getEntityLoadEventName(final EntityType extends Entity> et)
{
return "entity_loaded_" + ValueConversions.of(BuiltInRegistries.ENTITY_TYPE.getKey(et)).getString();
}
@@ -1058,7 +1122,7 @@ public class CarpetEventServer
.map(et -> Map.entry(et, new Event(getEntityLoadEventName(et), 1, true, false)
{
@Override
- public void onEntityAction(Entity entity, boolean created)
+ public void onEntityAction(final Entity entity, final boolean created)
{
handler.call(
() -> Collections.singletonList(new EntityValue(entity)),
@@ -1067,16 +1131,18 @@ public class CarpetEventServer
}
})).collect(Collectors.toUnmodifiableMap(Map.Entry::getKey, Map.Entry::getValue));
- public static String getEntityHandlerEventName(EntityType extends Entity> et)
+ public static String getEntityHandlerEventName(final EntityType extends Entity> et)
{
return "entity_handler_" + ValueConversions.of(BuiltInRegistries.ENTITY_TYPE.getKey(et)).getString();
}
public static final Map, Event> ENTITY_HANDLER = BuiltInRegistries.ENTITY_TYPE
.stream()
- .map(et -> Map.entry(et, new Event(getEntityHandlerEventName(et), 2, true, false) {
+ .map(et -> Map.entry(et, new Event(getEntityHandlerEventName(et), 2, true, false)
+ {
@Override
- public void onEntityAction(Entity entity, boolean created) {
+ public void onEntityAction(final Entity entity, final boolean created)
+ {
handler.call(
() -> Arrays.asList(new EntityValue(entity), BooleanValue.of(created)),
() -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel((ServerLevel) entity.level).withPermission(CarpetSettings.runPermissionLevel)
@@ -1091,11 +1157,13 @@ public class CarpetEventServer
public final CallbackList handler;
public final boolean isPublic; // public events can be targetted with __on_ defs
- public Event(String name, int reqArgs, boolean isGlobalOnly)
+
+ public Event(final String name, final int reqArgs, final boolean isGlobalOnly)
{
this(name, reqArgs, isGlobalOnly, true);
}
- public Event(String name, int reqArgs, boolean isGlobalOnly, boolean isPublic)
+
+ public Event(final String name, final int reqArgs, final boolean isGlobalOnly, final boolean isPublic)
{
this.name = name;
this.handler = new CallbackList(reqArgs, true, isGlobalOnly);
@@ -1103,34 +1171,43 @@ public class CarpetEventServer
byName.put(name, this);
}
- public static List getAllEvents(CarpetScriptServer server, Predicate predicate)
+ public static List getAllEvents(final CarpetScriptServer server, final Predicate predicate)
{
- List eventList = new ArrayList<>(CarpetEventServer.Event.byName.values());
+ final List eventList = new ArrayList<>(CarpetEventServer.Event.byName.values());
eventList.addAll(server.events.customEvents.values());
- if (predicate == null) return eventList;
- return eventList.stream().filter(predicate).collect(Collectors.toList());
+ if (predicate == null)
+ {
+ return eventList;
+ }
+ return eventList.stream().filter(predicate).toList();
}
- public static Event getEvent(String name, CarpetScriptServer server)
+ public static Event getEvent(final String name, final CarpetScriptServer server)
{
- if (byName.containsKey(name)) return byName.get(name);
+ if (byName.containsKey(name))
+ {
+ return byName.get(name);
+ }
return server.events.customEvents.get(name);
}
- public static Event getOrCreateCustom(String name, CarpetScriptServer server)
+ public static Event getOrCreateCustom(final String name, final CarpetScriptServer server)
{
- Event event = getEvent(name, server);
- if (event != null) return event;
+ final Event event = getEvent(name, server);
+ if (event != null)
+ {
+ return event;
+ }
return new Event(name, server);
}
- public static void removeAllHostEvents(CarpetScriptHost host)
+ public static void removeAllHostEvents(final CarpetScriptHost host)
{
byName.values().forEach((e) -> e.handler.removeAllCalls(host));
host.scriptServer().events.customEvents.values().forEach((e) -> e.handler.removeAllCalls(host));
}
- public static void transferAllHostEventsToChild(CarpetScriptHost host)
+ public static void transferAllHostEventsToChild(final CarpetScriptHost host)
{
byName.values().forEach((e) -> e.handler.createChildEvents(host));
host.scriptServer().events.customEvents.values().forEach((e) -> e.handler.createChildEvents(host));
@@ -1142,7 +1219,7 @@ public class CarpetEventServer
}
// custom event constructor
- private Event(String name, CarpetScriptServer server)
+ private Event(final String name, final CarpetScriptServer server)
{
this.name = name;
this.handler = new CallbackList(1, false, false);
@@ -1157,41 +1234,126 @@ public class CarpetEventServer
{
return handler.callList.size() > 0;
}
- public boolean deprecated() {return false;}
- //stubs for calls just to ease calls in vanilla code so they don't need to deal with scarpet value types
- public void onTick() { }
- public void onChunkEvent(ServerLevel world, ChunkPos chPos, boolean generated) { }
- public boolean onPlayerEvent(ServerPlayer player) {return false;}
- public boolean onPlayerMessage(ServerPlayer player, String message) {return false;}
- public void onPlayerStatistic(ServerPlayer player, Stat> stat, int amount) { }
- public void onMountControls(ServerPlayer player, float strafeSpeed, float forwardSpeed, boolean jumping, boolean sneaking) { }
- public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack) {return false;}
- public boolean onBlockAction(ServerPlayer player, BlockPos blockpos, Direction facing) {return false;}
- public boolean onBlockHit(ServerPlayer player, InteractionHand enumhand, BlockHitResult hitRes) {return false;}
- public boolean onBlockBroken(ServerPlayer player, BlockPos pos, BlockState previousBS) {return false;}
- public boolean onBlockPlaced(ServerPlayer player, BlockPos pos, InteractionHand enumhand, ItemStack itemstack) {return false;}
- public boolean onEntityHandAction(ServerPlayer player, Entity entity, InteractionHand enumhand) {return false;}
- public void onHandAction(ServerPlayer player, InteractionHand enumhand) { }
- public void onEntityAction(Entity entity, boolean created) { }
- public void onDimensionChange(ServerPlayer player, Vec3 from, Vec3 to, ResourceKey fromDim, ResourceKey dimTo) {}
- public boolean onDamage(Entity target, float amount, DamageSource source) {return false;}
- public boolean onRecipeSelected(ServerPlayer player, ResourceLocation recipe, boolean fullStack) {return false;}
- public void onSlotSwitch(ServerPlayer player, int from, int to) {}
- public void onTrade(ServerPlayer player, Merchant merchant, MerchantOffer tradeOffer) {}
- public void onExplosion(ServerLevel world, Entity e, Supplier attacker, double x, double y, double z, float power, boolean createFire, List affectedBlocks, List affectedEntities, Explosion.BlockInteraction type) { }
- public void onWorldEvent(ServerLevel world, BlockPos pos) { }
- public void onWorldEventFlag(ServerLevel world, BlockPos pos, int flag) { }
- public void onCarpetRuleChanges(CarpetRule> rule, CommandSourceStack source) { }
- public void onCustomPlayerEvent(ServerPlayer player, Object ... args)
+ public boolean deprecated()
{
- if (handler.reqArgs != (args.length+1))
- throw new InternalExpressionException("Expected "+handler.reqArgs+" arguments for "+name+", got "+(args.length+1));
+ return false;
+ }
+
+ //stubs for calls just to ease calls in vanilla code so they don't need to deal with scarpet value types
+ public void onTick()
+ {
+ }
+
+ public void onChunkEvent(final ServerLevel world, final ChunkPos chPos, final boolean generated)
+ {
+ }
+
+ public boolean onPlayerEvent(final ServerPlayer player)
+ {
+ return false;
+ }
+
+ public boolean onPlayerMessage(final ServerPlayer player, final String message)
+ {
+ return false;
+ }
+
+ public void onPlayerStatistic(final ServerPlayer player, final Stat> stat, final int amount)
+ {
+ }
+
+ public void onMountControls(final ServerPlayer player, final float strafeSpeed, final float forwardSpeed, final boolean jumping, final boolean sneaking)
+ {
+ }
+
+ public boolean onItemAction(final ServerPlayer player, final InteractionHand enumhand, final ItemStack itemstack)
+ {
+ return false;
+ }
+
+ public boolean onBlockAction(final ServerPlayer player, final BlockPos blockpos, final Direction facing)
+ {
+ return false;
+ }
+
+ public boolean onBlockHit(final ServerPlayer player, final InteractionHand enumhand, final BlockHitResult hitRes)
+ {
+ return false;
+ }
+
+ public boolean onBlockBroken(final ServerPlayer player, final BlockPos pos, final BlockState previousBS)
+ {
+ return false;
+ }
+
+ public boolean onBlockPlaced(final ServerPlayer player, final BlockPos pos, final InteractionHand enumhand, final ItemStack itemstack)
+ {
+ return false;
+ }
+
+ public boolean onEntityHandAction(final ServerPlayer player, final Entity entity, final InteractionHand enumhand)
+ {
+ return false;
+ }
+
+ public void onHandAction(final ServerPlayer player, final InteractionHand enumhand)
+ {
+ }
+
+ public void onEntityAction(final Entity entity, final boolean created)
+ {
+ }
+
+ public void onDimensionChange(final ServerPlayer player, final Vec3 from, final Vec3 to, final ResourceKey fromDim, final ResourceKey dimTo)
+ {
+ }
+
+ public boolean onDamage(final Entity target, final float amount, final DamageSource source)
+ {
+ return false;
+ }
+
+ public boolean onRecipeSelected(final ServerPlayer player, final ResourceLocation recipe, final boolean fullStack)
+ {
+ return false;
+ }
+
+ public void onSlotSwitch(final ServerPlayer player, final int from, final int to)
+ {
+ }
+
+ public void onTrade(final ServerPlayer player, final Merchant merchant, final MerchantOffer tradeOffer)
+ {
+ }
+
+ public void onExplosion(final ServerLevel world, final Entity e, final Supplier attacker, final double x, final double y, final double z, final float power, final boolean createFire, final List affectedBlocks, final List affectedEntities, final Explosion.BlockInteraction type)
+ {
+ }
+
+ public void onWorldEvent(final ServerLevel world, final BlockPos pos)
+ {
+ }
+
+ public void onWorldEventFlag(final ServerLevel world, final BlockPos pos, final int flag)
+ {
+ }
+
+ public void onCarpetRuleChanges(final CarpetRule> rule, final CommandSourceStack source)
+ {
+ }
+
+ public void onCustomPlayerEvent(final ServerPlayer player, final Object... args)
+ {
+ if (handler.reqArgs != (args.length + 1))
+ {
+ throw new InternalExpressionException("Expected " + handler.reqArgs + " arguments for " + name + ", got " + (args.length + 1));
+ }
handler.call(
() -> {
- List valArgs = new ArrayList<>();
+ final List valArgs = new ArrayList<>();
valArgs.add(EntityValue.of(player));
- for (Object o: args)
+ for (final Object o : args)
{
valArgs.add(ValueConversions.guess(player.getLevel(), o));
}
@@ -1199,14 +1361,17 @@ public class CarpetEventServer
}, player::createCommandSourceStack
);
}
- public void onCustomWorldEvent(ServerLevel world, Object ... args)
+
+ public void onCustomWorldEvent(final ServerLevel world, final Object... args)
{
if (handler.reqArgs != args.length)
- throw new InternalExpressionException("Expected "+handler.reqArgs+" arguments for "+name+", got "+args.length);
+ {
+ throw new InternalExpressionException("Expected " + handler.reqArgs + " arguments for " + name + ", got " + args.length);
+ }
handler.call(
() -> {
- List valArgs = new ArrayList<>();
- for (Object o: args)
+ final List valArgs = new ArrayList<>();
+ for (final Object o : args)
{
valArgs.add(ValueConversions.guess(world, o));
}
@@ -1217,7 +1382,7 @@ public class CarpetEventServer
}
- public CarpetEventServer(CarpetScriptServer scriptServer)
+ public CarpetEventServer(final CarpetScriptServer scriptServer)
{
this.scriptServer = scriptServer;
Event.clearAllBuiltinEvents();
@@ -1226,12 +1391,14 @@ public class CarpetEventServer
public void tick()
{
if (!TickSpeed.process_entities)
- return;
- Iterator eventIterator = scheduledCalls.iterator();
- List currentCalls = new ArrayList<>();
- while(eventIterator.hasNext())
{
- ScheduledCall call = eventIterator.next();
+ return;
+ }
+ final Iterator eventIterator = scheduledCalls.iterator();
+ final List currentCalls = new ArrayList<>();
+ while (eventIterator.hasNext())
+ {
+ final ScheduledCall call = eventIterator.next();
call.dueTime--;
if (call.dueTime <= 0)
{
@@ -1239,133 +1406,169 @@ public class CarpetEventServer
eventIterator.remove();
}
}
- for (ScheduledCall call: currentCalls)
+ for (final ScheduledCall call : currentCalls)
{
call.execute();
}
}
- public void scheduleCall(CarpetContext context, FunctionValue function, List args, long due)
+
+ public void scheduleCall(final CarpetContext context, final FunctionValue function, final List args, final long due)
{
scheduledCalls.add(new ScheduledCall(context, function, args, due));
}
- public void runScheduledCall(BlockPos origin, CommandSourceStack source, String hostname, CarpetScriptHost host, FunctionValue udf, List argv)
+ public void runScheduledCall(final BlockPos origin, final CommandSourceStack source, final String hostname, final CarpetScriptHost host, final FunctionValue udf, final List argv)
{
if (hostname != null && !scriptServer.modules.containsKey(hostname)) // well - scheduled call app got unloaded
+ {
return;
+ }
try
{
host.callUDF(origin, source, udf, argv);
}
- catch (NullPointerException | InvalidCallbackException | IntegrityException ignored) { }
+ catch (final NullPointerException | InvalidCallbackException | IntegrityException ignored)
+ {
+ }
}
- public CallbackResult runEventCall(CommandSourceStack sender, String hostname, String optionalTarget, FunctionValue udf, List argv)
+ public CallbackResult runEventCall(final CommandSourceStack sender, final String hostname, final String optionalTarget, final FunctionValue udf, final List argv)
{
- CarpetScriptHost appHost = scriptServer.getAppHostByName(hostname);
+ final CarpetScriptHost appHost = scriptServer.getAppHostByName(hostname);
// no such app
- if (appHost == null) return CallbackResult.FAIL;
+ if (appHost == null)
+ {
+ return CallbackResult.FAIL;
+ }
// dummy call for player apps that reside on the global copy - do not run them, but report as passes.
- if (appHost.isPerUser() && optionalTarget==null) return CallbackResult.PASS;
+ if (appHost.isPerUser() && optionalTarget == null)
+ {
+ return CallbackResult.PASS;
+ }
ServerPlayer target = null;
if (optionalTarget != null)
{
target = sender.getServer().getPlayerList().getPlayerByName(optionalTarget);
- if (target == null) return CallbackResult.FAIL;
+ if (target == null)
+ {
+ return CallbackResult.FAIL;
+ }
+ }
+ final CommandSourceStack source = sender.withPermission(CarpetSettings.runPermissionLevel);
+ final CarpetScriptHost executingHost = appHost.retrieveForExecution(sender, target);
+ if (executingHost == null)
+ {
+ return CallbackResult.FAIL;
}
- CommandSourceStack source = sender.withPermission(CarpetSettings.runPermissionLevel);
- CarpetScriptHost executingHost = appHost.retrieveForExecution(sender, target);
- if (executingHost == null) return CallbackResult.FAIL;
try
{
- Value returnValue = executingHost.callUDF(source.withPermission(CarpetSettings.runPermissionLevel), udf, argv);
+ final Value returnValue = executingHost.callUDF(source.withPermission(CarpetSettings.runPermissionLevel), udf, argv);
return returnValue instanceof StringValue && returnValue.getString().equals("cancel") ? CallbackResult.CANCEL : CallbackResult.SUCCESS;
}
- catch (NullPointerException | InvalidCallbackException | IntegrityException error)
+ catch (final NullPointerException | InvalidCallbackException | IntegrityException error)
{
CarpetScriptServer.LOG.error("Got exception when running event call ", error);
return CallbackResult.FAIL;
}
}
- public boolean addEventFromCommand(CommandSourceStack source, String event, String host, String funName)
+ public boolean addEventFromCommand(final CommandSourceStack source, final String event, final String host, final String funName)
{
- Event ev = Event.getEvent(event, CarpetServer.scriptServer);
+ final Event ev = Event.getEvent(event, CarpetServer.scriptServer);
if (ev == null)
{
return false;
}
- boolean added = ev.handler.addFromExternal(source, host, funName, h -> onEventAddedToHost(ev, h));
- if (added) Messenger.m(source, "gi Added " + funName + " to " + event);
+ final boolean added = ev.handler.addFromExternal(source, host, funName, h -> onEventAddedToHost(ev, h));
+ if (added)
+ {
+ Messenger.m(source, "gi Added " + funName + " to " + event);
+ }
return added;
}
- public void addBuiltInEvent(String event, ScriptHost host, FunctionValue function, List args)
+ public void addBuiltInEvent(final String event, final ScriptHost host, final FunctionValue function, final List args)
{
// this is globals only
- Event ev = Event.byName.get(event);
+ final Event ev = Event.byName.get(event);
onEventAddedToHost(ev, host);
- boolean success = ev.handler.addEventCallInternal(host, function, args==null?NOARGS:args);
- if (!success) throw new InternalExpressionException("Global event "+event+" requires "+ev.handler.reqArgs+", not "+(function.getNumParams()-((args==null)?0:args.size())));
+ final boolean success = ev.handler.addEventCallInternal(host, function, args == null ? NOARGS : args);
+ if (!success)
+ {
+ throw new InternalExpressionException("Global event " + event + " requires " + ev.handler.reqArgs + ", not " + (function.getNumParams() - ((args == null) ? 0 : args.size())));
+ }
}
- public boolean handleCustomEvent(String event, CarpetScriptHost host, FunctionValue function, List args)
+ public boolean handleCustomEvent(final String event, final CarpetScriptHost host, final FunctionValue function, final List args)
{
- Event ev = Event.getOrCreateCustom(event, scriptServer);
+ final Event ev = Event.getOrCreateCustom(event, scriptServer);
onEventAddedToHost(ev, host);
- return ev.handler.addEventCallInternal(host, function, args==null?NOARGS:args);
+ return ev.handler.addEventCallInternal(host, function, args == null ? NOARGS : args);
}
- public int signalEvent(String event, CarpetContext cc, ServerPlayer optionalTarget, List callArgs)
+ public int signalEvent(final String event, final CarpetContext cc, final ServerPlayer optionalTarget, final List callArgs)
{
- Event ev = Event.getEvent(event, ((CarpetScriptHost)cc.host).scriptServer());
- if (ev == null) return -1;
- return ev.handler.signal(cc.source(), optionalTarget, callArgs);
+ final Event ev = Event.getEvent(event, ((CarpetScriptHost) cc.host).scriptServer());
+ return ev == null ? -1 : ev.handler.signal(cc.source(), optionalTarget, callArgs);
}
- private void onEventAddedToHost(Event event, ScriptHost host)
+ private void onEventAddedToHost(final Event event, final ScriptHost host)
{
- if (event.deprecated()) host.issueDeprecation(event.name+" event");
+ if (event.deprecated())
+ {
+ host.issueDeprecation(event.name + " event");
+ }
event.handler.sortByPriority(this.scriptServer);
- //return !(event.globalOnly && (host.perUser || host.parent != null));
}
- public boolean removeEventFromCommand(CommandSourceStack source, String event, String funName)
+ public boolean removeEventFromCommand(final CommandSourceStack source, final String event, final String funName)
{
- Event ev = Event.getEvent(event, CarpetServer.scriptServer);
+ final Event ev = Event.getEvent(event, CarpetServer.scriptServer);
if (ev == null)
{
Messenger.m(source, "r Unknown event: " + event);
return false;
}
- Callback.Signature call = Callback.fromString(funName);
+ final Callback.Signature call = Callback.fromString(funName);
ev.handler.removeEventCall(call.host, call.target, call.function);
// could verified if actually removed
- Messenger.m(source, "gi Removed event: " + funName + " from "+event);
+ Messenger.m(source, "gi Removed event: " + funName + " from " + event);
return true;
}
- public boolean removeBuiltInEvent(String event, CarpetScriptHost host)
+
+ public boolean removeBuiltInEvent(final String event, final CarpetScriptHost host)
{
- Event ev = Event.getEvent(event, host.scriptServer());
- if (ev == null) return false;
+ final Event ev = Event.getEvent(event, host.scriptServer());
+ if (ev == null)
+ {
+ return false;
+ }
ev.handler.removeAllCalls(host);
return true;
}
- public void removeBuiltInEvent(String event, CarpetScriptHost host, String funName)
+ public void removeBuiltInEvent(final String event, final CarpetScriptHost host, final String funName)
{
- Event ev = Event.getEvent(event, host.scriptServer());
- if (ev != null) ev.handler.removeEventCall(host.getName(), host.user, funName);
+ final Event ev = Event.getEvent(event, host.scriptServer());
+ if (ev != null)
+ {
+ ev.handler.removeEventCall(host.getName(), host.user, funName);
+ }
}
- public void removeAllHostEvents(CarpetScriptHost host)
+ public void removeAllHostEvents(final CarpetScriptHost host)
{
// remove event handlers
Event.removeAllHostEvents(host);
if (host.isPerUser())
- for (ScriptHost child: host.userHosts.values()) Event.removeAllHostEvents((CarpetScriptHost) child);
+ {
+ for (final ScriptHost child : host.userHosts.values())
+ {
+ Event.removeAllHostEvents((CarpetScriptHost) child);
+ }
+ }
// remove scheduled calls
scheduledCalls.removeIf(sc -> sc.host != null && sc.host.equals(host.getName()));
}
-}
+}
\ No newline at end of file
diff --git a/src/main/java/carpet/script/CarpetExpression.java b/src/main/java/carpet/script/CarpetExpression.java
index 6873ff6e..ef78a103 100644
--- a/src/main/java/carpet/script/CarpetExpression.java
+++ b/src/main/java/carpet/script/CarpetExpression.java
@@ -25,12 +25,24 @@ public class CarpetExpression
private final CommandSourceStack source;
private final BlockPos origin;
private final Expression expr;
- // these are for extensions
- public Expression getExpr() {return expr;}
- public CommandSourceStack getSource() {return source;}
- public BlockPos getOrigin() {return origin;}
- public CarpetExpression(Module module, String expression, CommandSourceStack source, BlockPos origin)
+ // these are for extensions
+ public Expression getExpr()
+ {
+ return expr;
+ }
+
+ public CommandSourceStack getSource()
+ {
+ return source;
+ }
+
+ public BlockPos getOrigin()
+ {
+ return origin;
+ }
+
+ public CarpetExpression(final Module module, final String expression, final CommandSourceStack source, final BlockPos origin)
{
this.origin = origin;
this.source = source;
@@ -49,76 +61,80 @@ public class CarpetExpression
CarpetServer.extensions.forEach(e -> e.scarpetApi(this));
}
- public boolean fillAndScanCommand(ScriptHost host, int x, int y, int z)
+ public boolean fillAndScanCommand(final ScriptHost host, final int x, final int y, final int z)
{
if (CarpetServer.scriptServer.stopAll)
+ {
return false;
+ }
try
{
- Context context = new CarpetContext(host, source, origin).
+ final Context context = new CarpetContext(host, source, origin).
with("x", (c, t) -> new NumericValue(x - origin.getX()).bindTo("x")).
with("y", (c, t) -> new NumericValue(y - origin.getY()).bindTo("y")).
with("z", (c, t) -> new NumericValue(z - origin.getZ()).bindTo("z")).
with("_", (c, t) -> new BlockValue(null, source.getLevel(), new BlockPos(x, y, z)).bindTo("_"));
- Entity e = source.getEntity();
- if (e==null)
+ final Entity e = source.getEntity();
+ if (e == null)
{
- Value nullPlayer = Value.NULL.reboundedTo("p");
- context.with("p", (cc, tt) -> nullPlayer );
+ final Value nullPlayer = Value.NULL.reboundedTo("p");
+ context.with("p", (cc, tt) -> nullPlayer);
}
else
{
- Value playerValue = new EntityValue(e).bindTo("p");
+ final Value playerValue = new EntityValue(e).bindTo("p");
context.with("p", (cc, tt) -> playerValue);
}
- return CarpetServer.scriptServer.events.handleEvents.getWhileDisabled(()-> this.expr.eval(context).getBoolean());
+ return CarpetServer.scriptServer.events.handleEvents.getWhileDisabled(() -> this.expr.eval(context).getBoolean());
}
- catch (ExpressionException e)
+ catch (final ExpressionException e)
{
throw new CarpetExpressionException(e.getMessage(), e.stack);
}
- catch (ArithmeticException ae)
+ catch (final ArithmeticException ae)
{
- throw new CarpetExpressionException("Math doesn't compute... "+ae.getMessage(), null);
+ throw new CarpetExpressionException("Math doesn't compute... " + ae.getMessage(), null);
}
- catch (StackOverflowError soe)
+ catch (final StackOverflowError soe)
{
throw new CarpetExpressionException("Your thoughts are too deep", null);
}
}
- public Value scriptRunCommand(ScriptHost host, BlockPos pos)
+ public Value scriptRunCommand(final ScriptHost host, final BlockPos pos)
{
if (CarpetServer.scriptServer.stopAll)
+ {
throw new CarpetExpressionException("SCRIPTING PAUSED (unpause with /script resume)", null);
+ }
try
{
- Context context = new CarpetContext(host, source, origin).
+ final Context context = new CarpetContext(host, source, origin).
with("x", (c, t) -> new NumericValue(pos.getX() - origin.getX()).bindTo("x")).
with("y", (c, t) -> new NumericValue(pos.getY() - origin.getY()).bindTo("y")).
with("z", (c, t) -> new NumericValue(pos.getZ() - origin.getZ()).bindTo("z"));
- Entity e = source.getEntity();
- if (e==null)
+ final Entity e = source.getEntity();
+ if (e == null)
{
- Value nullPlayer = Value.NULL.reboundedTo("p");
- context.with("p", (cc, tt) -> nullPlayer );
+ final Value nullPlayer = Value.NULL.reboundedTo("p");
+ context.with("p", (cc, tt) -> nullPlayer);
}
else
{
- Value playerValue = new EntityValue(e).bindTo("p");
+ final Value playerValue = new EntityValue(e).bindTo("p");
context.with("p", (cc, tt) -> playerValue);
}
- return CarpetServer.scriptServer.events.handleEvents.getWhileDisabled(()-> this.expr.eval(context));
+ return CarpetServer.scriptServer.events.handleEvents.getWhileDisabled(() -> this.expr.eval(context));
}
- catch (ExpressionException e)
+ catch (final ExpressionException e)
{
throw new CarpetExpressionException(e.getMessage(), e.stack);
}
- catch (ArithmeticException ae)
+ catch (final ArithmeticException ae)
{
- throw new CarpetExpressionException("Math doesn't compute... "+ae.getMessage(), null);
+ throw new CarpetExpressionException("Math doesn't compute... " + ae.getMessage(), null);
}
- catch (StackOverflowError soe)
+ catch (final StackOverflowError soe)
{
throw new CarpetExpressionException("Your thoughts are too deep", null);
}
diff --git a/src/main/java/carpet/script/CarpetScriptHost.java b/src/main/java/carpet/script/CarpetScriptHost.java
index 7462db75..64a46da0 100644
--- a/src/main/java/carpet/script/CarpetScriptHost.java
+++ b/src/main/java/carpet/script/CarpetScriptHost.java
@@ -85,7 +85,7 @@ public class CarpetScriptHost extends ScriptHost
public AppStoreManager.StoreNode storeSource;
boolean hasCommand;
- private CarpetScriptHost(CarpetScriptServer server, Module code, boolean perUser, ScriptHost parent, Map config, Map argTypes, Predicate commandValidator, boolean isRuleApp)
+ private CarpetScriptHost(final CarpetScriptServer server, final Module code, final boolean perUser, final ScriptHost parent, final Map config, final Map argTypes, final Predicate commandValidator, final boolean isRuleApp)
{
super(code, server, perUser, parent);
this.saveTimeout = 0;
@@ -96,7 +96,7 @@ public class CarpetScriptHost extends ScriptHost
}
else if (parent != null)
{
- persistenceRequired = ((CarpetScriptHost)parent).persistenceRequired;
+ persistenceRequired = ((CarpetScriptHost) parent).persistenceRequired;
strict = parent.strict;
}
appConfig = config;
@@ -106,31 +106,31 @@ public class CarpetScriptHost extends ScriptHost
storeSource = null;
}
- public static CarpetScriptHost create(CarpetScriptServer scriptServer, Module module, boolean perPlayer, CommandSourceStack source, Predicate commandValidator, boolean isRuleApp, AppStoreManager.StoreNode storeSource)
+ public static CarpetScriptHost create(final CarpetScriptServer scriptServer, final Module module, final boolean perPlayer, final CommandSourceStack source, final Predicate commandValidator, final boolean isRuleApp, final AppStoreManager.StoreNode storeSource)
{
- CarpetScriptHost host = new CarpetScriptHost(scriptServer, module, perPlayer, null, Collections.emptyMap(), new HashMap<>(), commandValidator, isRuleApp);
+ final CarpetScriptHost host = new CarpetScriptHost(scriptServer, module, perPlayer, null, Collections.emptyMap(), new HashMap<>(), commandValidator, isRuleApp);
// parse code and convert to expression
if (module != null)
{
try
{
host.setChatErrorSnooper(source);
- CarpetExpression ex = new CarpetExpression(host.main, module.code(), source, new BlockPos(0, 0, 0));
+ final CarpetExpression ex = new CarpetExpression(host.main, module.code(), source, new BlockPos(0, 0, 0));
ex.getExpr().asATextSource();
host.storeSource = storeSource;
ex.scriptRunCommand(host, new BlockPos(source.getPosition()));
}
- catch (CarpetExpressionException e)
+ catch (final CarpetExpressionException e)
{
host.handleErrorWithStack("Error while evaluating expression", e);
throw new LoadException();
}
- catch (ArithmeticException ae) // is this branch ever reached? Seems like arithmetic exceptions are converted to CEEs earlier
+ catch (final ArithmeticException ae) // is this branch ever reached? Seems like arithmetic exceptions are converted to CEEs earlier
{
host.handleErrorWithStack("Math doesn't compute", ae);
throw new LoadException();
}
- catch (StackOverflowError soe)
+ catch (final StackOverflowError soe)
{
host.handleErrorWithStack("Your thoughts are too deep", soe);
}
@@ -142,42 +142,44 @@ public class CarpetScriptHost extends ScriptHost
return host;
}
- private static int execute(CommandContext ctx, String hostName, FunctionArgument funcSpec, List paramNames) throws CommandSyntaxException
+ private static int execute(final CommandContext ctx, final String hostName, final FunctionArgument funcSpec, final List paramNames) throws CommandSyntaxException
{
- CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet command", CarpetProfiler.TYPE.GENERAL);
- CarpetScriptHost cHost = CarpetServer.scriptServer.modules.get(hostName).retrieveOwnForExecution(ctx.getSource());
- List argNames = funcSpec.function.getArguments();
- if ((argNames.size()-funcSpec.args.size()) != paramNames.size())
- throw new SimpleCommandExceptionType(Component.literal("Target function "+funcSpec.function.getPrettyString()+" as wrong number of arguments, required "+paramNames.size()+", found "+argNames.size()+" with "+funcSpec.args.size()+" provided")).create();
- List args = new ArrayList<>(argNames.size());
- for (String s : paramNames)
+ final CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet command", CarpetProfiler.TYPE.GENERAL);
+ final CarpetScriptHost cHost = CarpetServer.scriptServer.modules.get(hostName).retrieveOwnForExecution(ctx.getSource());
+ final List argNames = funcSpec.function.getArguments();
+ if ((argNames.size() - funcSpec.args.size()) != paramNames.size())
+ {
+ throw new SimpleCommandExceptionType(Component.literal("Target function " + funcSpec.function.getPrettyString() + " as wrong number of arguments, required " + paramNames.size() + ", found " + argNames.size() + " with " + funcSpec.args.size() + " provided")).create();
+ }
+ final List args = new ArrayList<>(argNames.size());
+ for (final String s : paramNames)
{
args.add(CommandArgument.getValue(ctx, s, cHost));
}
args.addAll(funcSpec.args);
- Value response = cHost.handleCommand(ctx.getSource(), funcSpec.function, args);
- // will skip prints for new
- //if (!response.isNull()) Messenger.m(ctx.getSource(), "gi " + response.getString());
- int intres = (int) response.readInteger();
+ final Value response = cHost.handleCommand(ctx.getSource(), funcSpec.function, args);
+ final int intres = (int) response.readInteger();
CarpetProfiler.end_current_section(currentSection);
return intres;
}
public LiteralArgumentBuilder addPathToCommand(
- LiteralArgumentBuilder command,
- List path,
- FunctionArgument functionSpec
+ final LiteralArgumentBuilder command,
+ final List path,
+ final FunctionArgument functionSpec
) throws CommandSyntaxException
{
- String hostName = main.name();
- List commandArgs = path.stream().filter(t -> t.isArgument).map(t -> t.surface).collect(Collectors.toList());
- if (commandArgs.size() != (functionSpec.function.getNumParams()-functionSpec.args.size()) )
- throw CommandArgument.error("Number of parameters in function "+functionSpec.function.fullName()+" doesn't match parameters for a command");
+ final String hostName = main.name();
+ final List commandArgs = path.stream().filter(t -> t.isArgument).map(t -> t.surface).collect(Collectors.toList());
+ if (commandArgs.size() != (functionSpec.function.getNumParams() - functionSpec.args.size()))
+ {
+ throw CommandArgument.error("Number of parameters in function " + functionSpec.function.fullName() + " doesn't match parameters for a command");
+ }
if (path.isEmpty())
{
return command.executes((c) -> execute(c, hostName, functionSpec, Collections.emptyList()));
}
- List reversedPath = new ArrayList<>(path);
+ final List reversedPath = new ArrayList<>(path);
Collections.reverse(reversedPath);
ArgumentBuilder argChain = reversedPath.get(0).getCommandNode(this).executes(c -> execute(c, hostName, functionSpec, commandArgs));
for (int i = 1; i < reversedPath.size(); i++)
@@ -188,14 +190,14 @@ public class CarpetScriptHost extends ScriptHost
}
public LiteralArgumentBuilder getNewCommandTree(
- List,FunctionArgument>> entries, Predicate useValidator
+ final List, FunctionArgument>> entries, final Predicate useValidator
) throws CommandSyntaxException
{
- String hostName = main.name();
- Predicate configValidator = getCommandConfigPermissions();
+ final String hostName = main.name();
+ final Predicate configValidator = getCommandConfigPermissions();
LiteralArgumentBuilder command = literal(hostName).
- requires((player) -> useValidator.test(player) && configValidator.test(player));
- for (Pair,FunctionArgument> commandData : entries)
+ requires((player) -> useValidator.test(player) && configValidator.test(player));
+ for (final Pair, FunctionArgument> commandData : entries)
{
command = this.addPathToCommand(command, commandData.getKey(), commandData.getValue());
}
@@ -204,45 +206,51 @@ public class CarpetScriptHost extends ScriptHost
public Predicate getCommandConfigPermissions() throws CommandSyntaxException
{
- Value confValue = appConfig.get(StringValue.of("command_permission"));
- if (confValue == null) return s -> true;
- if (confValue instanceof NumericValue)
+ final Value confValue = appConfig.get(StringValue.of("command_permission"));
+ if (confValue == null)
{
- int level = ((NumericValue) confValue).getInt();
- if (level < 1 || level > 4) throw CommandArgument.error("Numeric permission level for custom commands should be between 1 and 4");
+ return s -> true;
+ }
+ if (confValue instanceof final NumericValue number)
+ {
+ final int level = number.getInt();
+ if (level < 1 || level > 4)
+ {
+ throw CommandArgument.error("Numeric permission level for custom commands should be between 1 and 4");
+ }
return s -> s.hasPermission(level);
}
- if (!(confValue instanceof FunctionValue))
+ if (!(confValue instanceof final FunctionValue fun))
{
- String perm = confValue.getString().toLowerCase(Locale.ROOT);
- switch (perm)
- {
- case "ops": return s -> s.hasPermission(2);
- case "server": return s -> !(s.getEntity() instanceof ServerPlayer);
- case "players": return s -> s.getEntity() instanceof ServerPlayer;
- case "all": return s -> true;
- default: throw CommandArgument.error("Unknown command permission: "+perm);
- }
+ final String perm = confValue.getString().toLowerCase(Locale.ROOT);
+ return switch (perm) {
+ case "ops" -> s -> s.hasPermission(2);
+ case "server" -> s -> !(s.getEntity() instanceof ServerPlayer);
+ case "players" -> s -> s.getEntity() instanceof ServerPlayer;
+ case "all" -> s -> true;
+ default -> throw CommandArgument.error("Unknown command permission: " + perm);
+ };
}
- FunctionValue fun = (FunctionValue) confValue;
- if (fun.getNumParams() != 1) throw CommandArgument.error("Custom command permission function should expect 1 argument");
- String hostName = getName();
+ if (fun.getNumParams() != 1)
+ {
+ throw CommandArgument.error("Custom command permission function should expect 1 argument");
+ }
+ final String hostName = getName();
return s -> {
try
{
- CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet command", CarpetProfiler.TYPE.GENERAL);
- CarpetScriptHost cHost = null;
- cHost = CarpetServer.scriptServer.modules.get(hostName).retrieveOwnForExecution(s);
- Value response = cHost.handleCommand(s, fun, Collections.singletonList(
- (s.getEntity() instanceof ServerPlayer)?new EntityValue(s.getEntity()):Value.NULL)
+ final CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet command", CarpetProfiler.TYPE.GENERAL);
+ final CarpetScriptHost cHost = CarpetServer.scriptServer.modules.get(hostName).retrieveOwnForExecution(s);
+ final Value response = cHost.handleCommand(s, fun, Collections.singletonList(
+ (s.getEntity() instanceof ServerPlayer) ? new EntityValue(s.getEntity()) : Value.NULL)
);
- boolean res = response.getBoolean();
+ final boolean res = response.getBoolean();
CarpetProfiler.end_current_section(currentSection);
return res;
}
- catch (CommandSyntaxException e)
+ catch (final CommandSyntaxException e)
{
- Messenger.m(s, "rb Unable to run app command: "+e.getMessage());
+ Messenger.m(s, "rb Unable to run app command: " + e.getMessage());
return false;
}
};
@@ -255,35 +263,45 @@ public class CarpetScriptHost extends ScriptHost
}
@Override
- protected void setupUserHost(ScriptHost host)
+ protected void setupUserHost(final ScriptHost host)
{
super.setupUserHost(host);
// transfer Events
- CarpetScriptHost child = (CarpetScriptHost) host;
+ final CarpetScriptHost child = (CarpetScriptHost) host;
CarpetEventServer.Event.transferAllHostEventsToChild(child);
- FunctionValue onStart = child.getFunction("__on_start");
- if (onStart != null) child.callNow(onStart, Collections.emptyList());
+ final FunctionValue onStart = child.getFunction("__on_start");
+ if (onStart != null)
+ {
+ child.callNow(onStart, Collections.emptyList());
+ }
}
@Override
- public void addUserDefinedFunction(Context ctx, Module module, String funName, FunctionValue function)
+ public void addUserDefinedFunction(final Context ctx, final Module module, final String funName, final FunctionValue function)
{
super.addUserDefinedFunction(ctx, module, funName, function);
- if (ctx.host.main != module) return; // not dealing with automatic imports / exports /configs / apps from imports
+ if (ctx.host.main != module)
+ {
+ return; // not dealing with automatic imports / exports /configs / apps from imports
+ }
if (funName.startsWith("__")) // potential fishy activity
{
if (funName.startsWith("__on_")) // here we can make a determination if we want to only accept events from main module.
{
// this is nasty, we have the host and function, yet we add it via names, but hey - works for now
- String event = funName.replaceFirst("__on_", "");
+ final String event = funName.replaceFirst("__on_", "");
if (CarpetEventServer.Event.byName.containsKey(event))
+ {
scriptServer().events.addBuiltInEvent(event, this, function, null);
+ }
}
else if (funName.equals("__config"))
{
// needs to be added as we read the code, cause other events may be affected.
if (!readConfig())
+ {
throw new InternalExpressionException("Invalid app config (via '__config()' function)");
+ }
}
}
}
@@ -292,43 +310,57 @@ public class CarpetScriptHost extends ScriptHost
{
try
{
- FunctionValue configFunction = getFunction("__config");
- if (configFunction == null) return false;
- Value ret = callNow(configFunction, Collections.emptyList());
- if (!(ret instanceof MapValue)) return false;
- Map config = ((MapValue) ret).getMap();
+ final FunctionValue configFunction = getFunction("__config");
+ if (configFunction == null)
+ {
+ return false;
+ }
+ final Value ret = callNow(configFunction, Collections.emptyList());
+ if (!(ret instanceof final MapValue map))
+ {
+ return false;
+ }
+ final Map config = map.getMap();
setPerPlayer(config.getOrDefault(new StringValue("scope"), new StringValue("player")).getString().equalsIgnoreCase("player"));
persistenceRequired = config.getOrDefault(new StringValue("stay_loaded"), Value.TRUE).getBoolean();
strict = config.getOrDefault(StringValue.of("strict"), Value.FALSE).getBoolean();
eventPriority = config.getOrDefault(new StringValue("event_priority"), Value.ZERO).readDoubleNumber();
// check requires
- Value loadRequirements = config.get(new StringValue("requires"));
- if (loadRequirements instanceof FunctionValue)
+ final Value loadRequirements = config.get(new StringValue("requires"));
+ if (loadRequirements instanceof final FunctionValue functionValue)
{
- Value reqResult = callNow((FunctionValue) loadRequirements, Collections.emptyList());
+ final Value reqResult = callNow(functionValue, Collections.emptyList());
if (reqResult.getBoolean()) // != false or null
+ {
throw new LoadException(reqResult.getString());
+ }
}
else
{
checkModVersionRequirements(loadRequirements);
- };
+ }
if (storeSource != null)
{
- Value resources = config.get(new StringValue("resources"));
+ final Value resources = config.get(new StringValue("resources"));
if (resources != null)
{
- if (!(resources instanceof ListValue)) throw new InternalExpressionException("App resources not defined as a list");
- for (Value resource : ((ListValue) resources).getItems())
+ if (!(resources instanceof final ListValue list))
+ {
+ throw new InternalExpressionException("App resources not defined as a list");
+ }
+ for (final Value resource : list.getItems())
{
AppStoreManager.addResource(this, storeSource, resource);
}
}
- Value libraries = config.get(new StringValue("libraries"));
+ final Value libraries = config.get(new StringValue("libraries"));
if (libraries != null)
{
- if (!(libraries instanceof ListValue)) throw new InternalExpressionException("App libraries not defined as a list");
- for (Value library : ((ListValue) libraries).getItems())
+ if (!(libraries instanceof final ListValue list))
+ {
+ throw new InternalExpressionException("App libraries not defined as a list");
+ }
+ for (final Value library : list.getItems())
{
AppStoreManager.addLibrary(this, storeSource, library);
}
@@ -336,22 +368,25 @@ public class CarpetScriptHost extends ScriptHost
}
appConfig = config;
}
- catch (NullPointerException ignored)
+ catch (final NullPointerException ignored)
{
return false;
}
return true;
}
- static class ListComparator> implements Comparator,?>>
+ static class ListComparator> implements Comparator, ?>>
{
@Override
- public int compare(Pair,?> p1, Pair,?> p2) {
- List o1 = p1.getKey();
- List o2 = p2.getKey();
- for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) {
- int c = o1.get(i).compareTo(o2.get(i));
- if (c != 0) {
+ public int compare(final Pair, ?> p1, final Pair, ?> p2)
+ {
+ final List o1 = p1.getKey();
+ final List o2 = p2.getKey();
+ for (int i = 0; i < Math.min(o1.size(), o2.size()); i++)
+ {
+ final int c = o1.get(i).compareTo(o2.get(i));
+ if (c != 0)
+ {
return c;
}
}
@@ -360,7 +395,8 @@ public class CarpetScriptHost extends ScriptHost
}
// Used to ensure app gets marked as holding command from a central place
- private void registerCommand(LiteralArgumentBuilder command) {
+ private void registerCommand(final LiteralArgumentBuilder command)
+ {
scriptServer().server.getCommands().getDispatcher().register(command);
hasCommand = true;
}
@@ -368,32 +404,37 @@ public class CarpetScriptHost extends ScriptHost
public void readCustomArgumentTypes() throws CommandSyntaxException
{
// read custom arguments
- Value arguments = appConfig.get(StringValue.of("arguments"));
+ final Value arguments = appConfig.get(StringValue.of("arguments"));
if (arguments != null)
{
- if (!(arguments instanceof MapValue))
- throw CommandArgument.error("'arguments' element in config should be a map");
- appArgTypes.clear();
- for (Map.Entry typeData : ((MapValue)arguments).getMap().entrySet())
+ if (!(arguments instanceof final MapValue map))
{
- String argument = typeData.getKey().getString();
- Value spec = typeData.getValue();
- if (!(spec instanceof MapValue)) throw CommandArgument.error("Spec for '"+argument+"' should be a map");
- Map specData = ((MapValue) spec).getMap().entrySet().stream().collect(Collectors.toMap(e -> e.getKey().getString(), Map.Entry::getValue));
+ throw CommandArgument.error("'arguments' element in config should be a map");
+ }
+ appArgTypes.clear();
+ for (final Map.Entry typeData : map.getMap().entrySet())
+ {
+ final String argument = typeData.getKey().getString();
+ final Value spec = typeData.getValue();
+ if (!(spec instanceof final MapValue specMap))
+ {
+ throw CommandArgument.error("Spec for '" + argument + "' should be a map");
+ }
+ final Map specData = specMap.getMap().entrySet().stream().collect(Collectors.toMap(e -> e.getKey().getString(), Map.Entry::getValue));
appArgTypes.put(argument, CommandArgument.buildFromConfig(argument, specData, this));
}
}
}
- public Boolean addAppCommands(Consumer notifier)
+ public Boolean addAppCommands(final Consumer notifier)
{
try
{
readCustomArgumentTypes();
}
- catch (CommandSyntaxException e)
+ catch (final CommandSyntaxException e)
{
- notifier.accept(Messenger.c("r Error when handling of setting up custom argument types: "+e.getMessage()));
+ notifier.accept(Messenger.c("r Error when handling of setting up custom argument types: " + e.getMessage()));
return false;
}
if (appConfig.get(StringValue.of("commands")) != null)
@@ -405,17 +446,15 @@ public class CarpetScriptHost extends ScriptHost
}
try
{
- LiteralArgumentBuilder command = readCommands(commandValidator);
+ final LiteralArgumentBuilder command = readCommands(commandValidator);
if (command != null)
{
registerCommand(command);
return true;
}
- else {
- return false;
- }
+ return false;
}
- catch (CommandSyntaxException cse)
+ catch (final CommandSyntaxException cse)
{
// failed
notifier.accept(Messenger.c("r Failed to build command system: ", cse.getRawMessage()));
@@ -425,30 +464,36 @@ public class CarpetScriptHost extends ScriptHost
}
return addLegacyCommand(notifier);
}
-
- public void checkModVersionRequirements(Value reqs) {
+
+ public void checkModVersionRequirements(final Value reqs)
+ {
if (reqs == null)
+ {
return;
- if (!(reqs instanceof MapValue))
+ }
+ if (!(reqs instanceof final MapValue map))
{
throw new InternalExpressionException("`requires` field must be a map of mod dependencies or a function to be executed");
}
- Map requirements = ((MapValue)reqs).getMap();
- for (Entry requirement : requirements.entrySet())
+ final Map requirements = map.getMap();
+ for (final Entry requirement : requirements.entrySet())
{
- String requiredModId = requirement.getKey().getString();
- String stringPredicate = requirement.getValue().getString();
- VersionPredicate predicate;
- try {
+ final String requiredModId = requirement.getKey().getString();
+ final String stringPredicate = requirement.getValue().getString();
+ final VersionPredicate predicate;
+ try
+ {
predicate = VersionPredicate.parse(stringPredicate);
- } catch (VersionParsingException e) {
+ }
+ catch (final VersionParsingException e)
+ {
throw new InternalExpressionException("Failed to parse version conditions for '" + requiredModId + "' in 'requires': " + e.getMessage());
}
- ModContainer mod = FabricLoader.getInstance().getModContainer(requiredModId).orElse(null);
+ final ModContainer mod = FabricLoader.getInstance().getModContainer(requiredModId).orElse(null);
if (mod != null)
{
- Version presentVersion = mod.getMetadata().getVersion();
+ final Version presentVersion = mod.getMetadata().getVersion();
if (predicate.test(presentVersion) || (FabricLoader.getInstance().isDevelopmentEnvironment() && !(presentVersion instanceof SemanticVersion)))
{ // in a dev env, mod version is usually replaced with ${version}, and that isn't semantic
continue;
@@ -458,10 +503,12 @@ public class CarpetScriptHost extends ScriptHost
}
}
- private Boolean addLegacyCommand(Consumer notifier)
+ private Boolean addLegacyCommand(final Consumer notifier)
{
- if (main == null) return false;
- if (getFunction("__command") == null) return false;
+ if (main == null || getFunction("__command") == null)
+ {
+ return false;
+ }
if (scriptServer().isInvalidCommandRoot(getName()))
{
@@ -469,43 +516,46 @@ public class CarpetScriptHost extends ScriptHost
return null;
}
- Predicate configValidator;
+ final Predicate configValidator;
try
{
configValidator = getCommandConfigPermissions();
}
- catch (CommandSyntaxException e)
+ catch (final CommandSyntaxException e)
{
- notifier.accept(Messenger.c("rb "+e.getMessage()));
+ notifier.accept(Messenger.c("rb " + e.getMessage()));
return null;
}
- String hostName = getName();
+ final String hostName = getName();
LiteralArgumentBuilder command = literal(hostName).
requires((player) -> commandValidator.test(player) && configValidator.test(player)).
- executes( (c) ->
+ executes((c) ->
{
- CarpetScriptHost targetHost = scriptServer().modules.get(hostName).retrieveOwnForExecution(c.getSource());
- Value response = targetHost.handleCommandLegacy(c.getSource(),"__command", null, "");
- if (!response.isNull()) Messenger.m(c.getSource(), "gi "+response.getString());
- return (int)response.readInteger();
+ final CarpetScriptHost targetHost = scriptServer().modules.get(hostName).retrieveOwnForExecution(c.getSource());
+ final Value response = targetHost.handleCommandLegacy(c.getSource(), "__command", null, "");
+ if (!response.isNull())
+ {
+ Messenger.m(c.getSource(), "gi " + response.getString());
+ }
+ return (int) response.readInteger();
});
- boolean hasTypeSupport = appConfig.getOrDefault(StringValue.of("legacy_command_type_support"), Value.FALSE).getBoolean();
+ final boolean hasTypeSupport = appConfig.getOrDefault(StringValue.of("legacy_command_type_support"), Value.FALSE).getBoolean();
- for (String function : globalFunctionNames(main, s -> !s.startsWith("_")).sorted().collect(Collectors.toList()))
+ for (final String function : globalFunctionNames(main, s -> !s.startsWith("_")).sorted().collect(Collectors.toList()))
{
if (hasTypeSupport)
{
try
{
- FunctionValue functionValue = getFunction(function);
+ final FunctionValue functionValue = getFunction(function);
command = addPathToCommand(
command,
CommandToken.parseSpec(CommandToken.specFromSignature(functionValue), this),
FunctionArgument.fromCommandSpec(this, functionValue)
);
}
- catch (CommandSyntaxException e)
+ catch (final CommandSyntaxException e)
{
return false;
}
@@ -516,17 +566,23 @@ public class CarpetScriptHost extends ScriptHost
then(literal(function).
requires((player) -> scriptServer().modules.get(hostName).getFunction(function) != null).
executes((c) -> {
- CarpetScriptHost targetHost = scriptServer().modules.get(hostName).retrieveOwnForExecution(c.getSource());
- Value response = targetHost.handleCommandLegacy(c.getSource(),function, null, "");
- if (!response.isNull()) Messenger.m(c.getSource(), "gi " + response.getString());
+ final CarpetScriptHost targetHost = scriptServer().modules.get(hostName).retrieveOwnForExecution(c.getSource());
+ final Value response = targetHost.handleCommandLegacy(c.getSource(), function, null, "");
+ if (!response.isNull())
+ {
+ Messenger.m(c.getSource(), "gi " + response.getString());
+ }
return (int) response.readInteger();
}).
then(argument("args...", StringArgumentType.greedyString()).
- executes( (c) -> {
- CarpetScriptHost targetHost = scriptServer().modules.get(hostName).retrieveOwnForExecution(c.getSource());
- Value response = targetHost.handleCommandLegacy(c.getSource(),function, null, StringArgumentType.getString(c, "args..."));
- if (!response.isNull()) Messenger.m(c.getSource(), "gi "+response.getString());
- return (int)response.readInteger();
+ executes((c) -> {
+ final CarpetScriptHost targetHost = scriptServer().modules.get(hostName).retrieveOwnForExecution(c.getSource());
+ final Value response = targetHost.handleCommandLegacy(c.getSource(), function, null, StringArgumentType.getString(c, "args..."));
+ if (!response.isNull())
+ {
+ Messenger.m(c.getSource(), "gi " + response.getString());
+ }
+ return (int) response.readInteger();
})));
}
}
@@ -534,39 +590,48 @@ public class CarpetScriptHost extends ScriptHost
return true;
}
- public LiteralArgumentBuilder readCommands(Predicate useValidator) throws CommandSyntaxException
+ public LiteralArgumentBuilder readCommands(final Predicate useValidator) throws CommandSyntaxException
{
- Value commands = appConfig.get(StringValue.of("commands"));
+ final Value commands = appConfig.get(StringValue.of("commands"));
- if (commands == null) return null;
- if (!(commands instanceof MapValue))
- throw CommandArgument.error("'commands' element in config should be a map");
- List,FunctionArgument>> commandEntries = new ArrayList<>();
-
- for (Map.Entry commandsData : ((MapValue)commands).getMap().entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toList()))
+ if (commands == null)
{
- List elements = CommandToken.parseSpec(commandsData.getKey().getString(), this);
- FunctionArgument funSpec = FunctionArgument.fromCommandSpec(this, commandsData.getValue());
+ return null;
+ }
+ if (!(commands instanceof final MapValue map))
+ {
+ throw CommandArgument.error("'commands' element in config should be a map");
+ }
+ final List, FunctionArgument>> commandEntries = new ArrayList<>();
+
+ for (final Map.Entry commandsData : map.getMap().entrySet().stream().sorted(Entry.comparingByKey()).toList())
+ {
+ final List elements = CommandToken.parseSpec(commandsData.getKey().getString(), this);
+ final FunctionArgument funSpec = FunctionArgument.fromCommandSpec(this, commandsData.getValue());
commandEntries.add(Pair.of(elements, funSpec));
}
commandEntries.sort(new ListComparator<>());
if (!appConfig.getOrDefault(StringValue.of("allow_command_conflicts"), Value.FALSE).getBoolean())
{
- for (int i = 0; i < commandEntries.size()-1; i++)
+ for (int i = 0; i < commandEntries.size() - 1; i++)
{
- List first = commandEntries.get(i).getKey();
- List other = commandEntries.get(i+1).getKey();
- int checkSize = Math.min(first.size(), other.size());
+ final List first = commandEntries.get(i).getKey();
+ final List other = commandEntries.get(i + 1).getKey();
+ final int checkSize = Math.min(first.size(), other.size());
for (int t = 0; t < checkSize; t++)
{
- CommandToken tik = first.get(t);
- CommandToken tok = other.get(t);
+ final CommandToken tik = first.get(t);
+ final CommandToken tok = other.get(t);
if (tik.isArgument && tok.isArgument && !tik.surface.equals(tok.surface))
- throw CommandArgument.error("Conflicting commands: \n"+
- " - [" +first.stream().map(tt -> tt.surface).collect(Collectors.joining(" ")) + "] at "+tik.surface+"\n"+
- " - [" +other.stream().map(tt -> tt.surface).collect(Collectors.joining(" ")) + "] at "+tok.surface+"\n");
+ {
+ throw CommandArgument.error("Conflicting commands: \n" +
+ " - [" + first.stream().map(tt -> tt.surface).collect(Collectors.joining(" ")) + "] at " + tik.surface + "\n" +
+ " - [" + other.stream().map(tt -> tt.surface).collect(Collectors.joining(" ")) + "] at " + tok.surface + "\n");
+ }
if (!tik.equals(tok))
+ {
break;
+ }
}
}
}
@@ -574,37 +639,39 @@ public class CarpetScriptHost extends ScriptHost
}
@Override
- protected Module getModuleOrLibraryByName(String name)
+ protected Module getModuleOrLibraryByName(final String name)
{
- Module module = scriptServer().getModule(name, true);
+ final Module module = scriptServer().getModule(name, true);
if (module == null)
- throw new InternalExpressionException("Unable to locate package: "+name);
+ {
+ throw new InternalExpressionException("Unable to locate package: " + name);
+ }
return module;
}
@Override
- protected void runModuleCode(Context c, Module module)
+ protected void runModuleCode(final Context c, final Module module)
{
- CarpetContext cc = (CarpetContext)c;
- CarpetExpression ex = new CarpetExpression(module, module.code(), cc.source(), cc.origin());
+ final CarpetContext cc = (CarpetContext) c;
+ final CarpetExpression ex = new CarpetExpression(module, module.code(), cc.source(), cc.origin());
ex.getExpr().asATextSource();
ex.scriptRunCommand(this, cc.origin());
}
@Override
- public void delFunction(Module module, String funName)
+ public void delFunction(final Module module, final String funName)
{
super.delFunction(module, funName);
// mcarpet
if (funName.startsWith("__on_"))
{
// this is nasty, we have the host and function, yet we add it via names, but hey - works for now
- String event = funName.replaceFirst("__on_","");
+ final String event = funName.replaceFirst("__on_", "");
scriptServer().events.removeBuiltInEvent(event, this, funName);
}
}
- public CarpetScriptHost retrieveForExecution(CommandSourceStack source, ServerPlayer player)
+ public CarpetScriptHost retrieveForExecution(final CommandSourceStack source, final ServerPlayer player)
{
CarpetScriptHost target = null;
if (!perUser)
@@ -615,96 +682,116 @@ public class CarpetScriptHost extends ScriptHost
{
target = (CarpetScriptHost) retrieveForExecution(player.getScoreboardName());
}
- if (target != null && target.errorSnooper == null) target.setChatErrorSnooper(source);
+ if (target != null && target.errorSnooper == null)
+ {
+ target.setChatErrorSnooper(source);
+ }
return target;
}
- public CarpetScriptHost retrieveOwnForExecution(CommandSourceStack source) throws CommandSyntaxException
+ public CarpetScriptHost retrieveOwnForExecution(final CommandSourceStack source) throws CommandSyntaxException
{
if (!perUser)
{
- if (errorSnooper == null) setChatErrorSnooper(source);
+ if (errorSnooper == null)
+ {
+ setChatErrorSnooper(source);
+ }
return this;
}
// user based
- ServerPlayer player;
+ final ServerPlayer player;
try
{
player = source.getPlayerOrException();
}
- catch (CommandSyntaxException ignored)
+ catch (final CommandSyntaxException ignored)
{
throw new SimpleCommandExceptionType(Component.literal("Cannot run player based apps without the player context")).create();
}
- CarpetScriptHost userHost = (CarpetScriptHost)retrieveForExecution(player.getScoreboardName());
- if (userHost.errorSnooper == null) userHost.setChatErrorSnooper(source);
+ final CarpetScriptHost userHost = (CarpetScriptHost) retrieveForExecution(player.getScoreboardName());
+ if (userHost.errorSnooper == null)
+ {
+ userHost.setChatErrorSnooper(source);
+ }
return userHost;
}
- public Value handleCommandLegacy(CommandSourceStack source, String call, List coords, String arg)
+ public Value handleCommandLegacy(final CommandSourceStack source, final String call, final List coords, final String arg)
{
try
{
- CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet command", CarpetProfiler.TYPE.GENERAL);
- Value res = callLegacy(source, call, coords, arg);
+ final CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet command", CarpetProfiler.TYPE.GENERAL);
+ final Value res = callLegacy(source, call, coords, arg);
CarpetProfiler.end_current_section(currentSection);
return res;
}
- catch (CarpetExpressionException exc)
+ catch (final CarpetExpressionException exc)
{
handleErrorWithStack("Error while running custom command", exc);
}
- catch (ArithmeticException ae)
+ catch (final ArithmeticException ae)
{
handleErrorWithStack("Math doesn't compute", ae);
}
- catch (StackOverflowError soe)
+ catch (final StackOverflowError soe)
{
handleErrorWithStack("Your thoughts are too deep", soe);
}
return Value.NULL;
}
- public Value handleCommand(CommandSourceStack source, FunctionValue function, List args)
+ public Value handleCommand(final CommandSourceStack source, final FunctionValue function, final List args)
{
try
{
return scriptServer().events.handleEvents.getWhileDisabled(() -> call(source, function, args));
}
- catch (CarpetExpressionException exc)
+ catch (final CarpetExpressionException exc)
{
handleErrorWithStack("Error while running custom command", exc);
}
- catch (ArithmeticException ae)
+ catch (final ArithmeticException ae)
{
handleErrorWithStack("Math doesn't compute", ae);
}
- catch (StackOverflowError soe)
+ catch (final StackOverflowError soe)
{
handleErrorWithStack("Your thoughts are too deep", soe);
}
return Value.NULL;
}
- public Value callLegacy(CommandSourceStack source, String call, List coords, String arg)
+ public Value callLegacy(final CommandSourceStack source, final String call, final List coords, final String arg)
{
if (CarpetServer.scriptServer.stopAll)
+ {
throw new CarpetExpressionException("SCARPET PAUSED (unpause with /script resume)", null);
- FunctionValue function = getFunction(call);
+ }
+ final FunctionValue function = getFunction(call);
if (function == null)
+ {
throw new CarpetExpressionException("Couldn't find function '" + call + "' in app '" + this.getName() + "'", null);
- List argv = new ArrayList<>();
+ }
+ final List argv = new ArrayList<>();
if (coords != null)
- for (Integer i: coords)
- argv.add( (c, t) -> new NumericValue(i));
+ {
+ for (final Integer i : coords)
+ {
+ argv.add((c, t) -> new NumericValue(i));
+ }
+ }
String sign = "";
- for (Tokenizer.Token tok : Tokenizer.simplepass(arg))
+ for (final Tokenizer.Token tok : Tokenizer.simplepass(arg))
{
switch (tok.type)
{
case VARIABLE:
- LazyValue var = getGlobalVariable(tok.surface);
- if (var != null) argv.add(var);
+ final LazyValue variable = getGlobalVariable(tok.surface);
+ if (variable != null)
+ {
+ argv.add(variable);
+ }
break;
case STRINGPARAM:
argv.add((c, t) -> new StringValue(tok.surface));
@@ -714,31 +801,30 @@ public class CarpetScriptHost extends ScriptHost
case LITERAL:
try
{
- String finalSign = sign;
- argv.add((c, t) ->new NumericValue(finalSign+tok.surface));
+ final String finalSign = sign;
+ argv.add((c, t) -> new NumericValue(finalSign + tok.surface));
sign = "";
}
- catch (NumberFormatException exception)
+ catch (final NumberFormatException exception)
{
- throw new CarpetExpressionException("Fail: "+sign+tok.surface+" seems like a number but it is" +
+ throw new CarpetExpressionException("Fail: " + sign + tok.surface + " seems like a number but it is" +
" not a number. Use quotes to ensure its a string", null);
}
break;
case HEX_LITERAL:
try
{
- String finalSign = sign;
- argv.add((c, t) -> new NumericValue(new BigInteger(finalSign+tok.surface.substring(2), 16).doubleValue()));
+ final String finalSign = sign;
+ argv.add((c, t) -> new NumericValue(new BigInteger(finalSign + tok.surface.substring(2), 16).doubleValue()));
sign = "";
}
- catch (NumberFormatException exception)
+ catch (final NumberFormatException exception)
{
- throw new CarpetExpressionException("Fail: "+sign+tok.surface+" seems like a number but it is" +
+ throw new CarpetExpressionException("Fail: " + sign + tok.surface + " seems like a number but it is" +
" not a number. Use quotes to ensure its a string", null);
}
break;
- case OPERATOR:
- case UNARY_OPERATOR:
+ case OPERATOR, UNARY_OPERATOR:
if ((tok.surface.equals("-") || tok.surface.equals("-u")) && sign.isEmpty())
{
sign = "-";
@@ -750,22 +836,19 @@ public class CarpetScriptHost extends ScriptHost
}
break;
case FUNCTION:
- throw new CarpetExpressionException("Fail: passing functions like "+tok.surface+"() to invoke is " +
+ throw new CarpetExpressionException("Fail: passing functions like " + tok.surface + "() to invoke is " +
"not allowed", null);
- case OPEN_PAREN:
- case COMMA:
- case CLOSE_PAREN:
- case MARKER:
- throw new CarpetExpressionException("Fail: "+tok.surface+" is not allowed in invoke", null);
+ case OPEN_PAREN, COMMA, CLOSE_PAREN, MARKER:
+ throw new CarpetExpressionException("Fail: " + tok.surface + " is not allowed in invoke", null);
}
}
- List args = function.getArguments();
+ final List args = function.getArguments();
if (argv.size() != args.size())
{
- String error = "Fail: stored function "+call+" takes "+args.size()+" arguments, not "+argv.size()+ ":\n";
+ String error = "Fail: stored function " + call + " takes " + args.size() + " arguments, not " + argv.size() + ":\n";
for (int i = 0; i < max(argv.size(), args.size()); i++)
{
- error += (i "+(i " + (i < argv.size() ? argv.get(i).evalValue(null).getString() : "??") + "\n";
}
throw new CarpetExpressionException(error, null);
}
@@ -773,97 +856,102 @@ public class CarpetScriptHost extends ScriptHost
{
// TODO: this is just for now - invoke would be able to invoke other hosts scripts
assertAppIntegrity(function.getModule());
- Context context = new CarpetContext(this, source);
+ final Context context = new CarpetContext(this, source);
return scriptServer().events.handleEvents.getWhileDisabled(() -> function.getExpression().evalValue(
() -> function.lazyEval(context, Context.VOID, function.getExpression(), function.getToken(), argv),
context,
Context.VOID
));
}
- catch (ExpressionException e)
+ catch (final ExpressionException e)
{
throw new CarpetExpressionException(e.getMessage(), e.stack);
}
}
- public Value call(CommandSourceStack source, FunctionValue function, List argv)
+ public Value call(final CommandSourceStack source, final FunctionValue function, final List argv)
{
if (CarpetServer.scriptServer.stopAll)
+ {
throw new CarpetExpressionException("SCARPET PAUSED (unpause with /script resume)", null);
+ }
- List args = function.getArguments();
+ final List args = function.getArguments();
if (argv.size() != args.size())
{
- String error = "Fail: stored function "+function.getPrettyString()+" takes "+args.size()+" arguments, not "+argv.size()+ ":\n";
+ String error = "Fail: stored function " + function.getPrettyString() + " takes " + args.size() + " arguments, not " + argv.size() + ":\n";
for (int i = 0; i < max(argv.size(), args.size()); i++)
{
- error += (i "+(i " + (i < argv.size() ? argv.get(i).getString() : "??") + "\n";
}
throw new CarpetExpressionException(error, null);
}
try
{
assertAppIntegrity(function.getModule());
- Context context = new CarpetContext(this, source);
+ final Context context = new CarpetContext(this, source);
return function.getExpression().evalValue(
() -> function.execute(context, Context.VOID, function.getExpression(), function.getToken(), argv),
context,
Context.VOID
);
}
- catch (ExpressionException e)
+ catch (final ExpressionException e)
{
throw new CarpetExpressionException(e.getMessage(), e.stack);
}
}
- public Value callUDF(CommandSourceStack source, FunctionValue fun, List argv) throws InvalidCallbackException, IntegrityException
+ public Value callUDF(final CommandSourceStack source, final FunctionValue fun, final List argv) throws InvalidCallbackException, IntegrityException
{
return callUDF(BlockPos.ZERO, source, fun, argv);
}
- public Value callUDF(BlockPos origin, CommandSourceStack source, FunctionValue fun, List argv) throws InvalidCallbackException, IntegrityException
+ public Value callUDF(final BlockPos origin, final CommandSourceStack source, final FunctionValue fun, final List argv) throws InvalidCallbackException, IntegrityException
{
if (CarpetServer.scriptServer.stopAll)
+ {
return Value.NULL;
- try { // cause we can't throw checked exceptions in lambda. Left if be until need to handle these more gracefully
+ }
+ try
+ { // cause we can't throw checked exceptions in lambda. Left if be until need to handle these more gracefully
fun.assertArgsOk(argv, (b) -> {
throw new InternalExpressionException("");
});
}
- catch (InternalExpressionException ignored)
+ catch (final InternalExpressionException ignored)
{
throw new InvalidCallbackException();
}
try
{
assertAppIntegrity(fun.getModule());
- Context context = new CarpetContext(this, source, origin);
+ final Context context = new CarpetContext(this, source, origin);
return fun.getExpression().evalValue(
() -> fun.execute(context, Context.VOID, fun.getExpression(), fun.getToken(), argv),
context,
Context.VOID);
}
- catch (ExpressionException e)
+ catch (final ExpressionException e)
{
handleExpressionException("Callback failed", e);
}
return Value.NULL;
}
- public Value callNow(FunctionValue fun, List arguments)
+ public Value callNow(final FunctionValue fun, final List arguments)
{
- ServerPlayer player = (user==null)?null:scriptServer().server.getPlayerList().getPlayerByName(user);
- CommandSourceStack source = (player != null)?player.createCommandSourceStack():scriptServer().server.createCommandSourceStack();
- return scriptServer().events.handleEvents.getWhileDisabled(()->{
- try
- {
- return callUDF(source, fun, arguments);
- }
- catch (InvalidCallbackException ignored)
- {
- return Value.NULL;
- }
+ final ServerPlayer player = (user == null) ? null : scriptServer().server.getPlayerList().getPlayerByName(user);
+ final CommandSourceStack source = (player != null) ? player.createCommandSourceStack() : scriptServer().server.createCommandSourceStack();
+ return scriptServer().events.handleEvents.getWhileDisabled(() -> {
+ try
+ {
+ return callUDF(source, fun, arguments);
+ }
+ catch (final InvalidCallbackException ignored)
+ {
+ return Value.NULL;
+ }
});
}
@@ -872,26 +960,28 @@ public class CarpetScriptHost extends ScriptHost
public void onClose()
{
super.onClose();
- FunctionValue closing = getFunction("__on_close");
+ final FunctionValue closing = getFunction("__on_close");
if (closing != null && (parent != null || !isPerUser()))
- // either global instance of a global task, or
- // user host in player scoped app
+ // either global instance of a global task, or
+ // user host in player scoped app
{
callNow(closing, Collections.emptyList());
}
if (user == null)
{
- String markerName = Auxiliary.MARKER_STRING + "_" + ((getName() == null) ? "" : getName());
- for (ServerLevel world : scriptServer().server.getAllLevels())
+ final String markerName = Auxiliary.MARKER_STRING + "_" + ((getName() == null) ? "" : getName());
+ for (final ServerLevel world : scriptServer().server.getAllLevels())
{
- for (Entity e : world.getEntities(EntityType.ARMOR_STAND, (as) -> as.getTags().contains(markerName)))
+ for (final Entity e : world.getEntities(EntityType.ARMOR_STAND, (as) -> as.getTags().contains(markerName)))
{
e.discard();
}
}
if (this.saveTimeout > 0)
+ {
dumpState();
+ }
}
}
@@ -905,26 +995,36 @@ public class CarpetScriptHost extends ScriptHost
return Module.getData(main);
}
- public Tag readFileTag(FileArgument fdesc)
+ public Tag readFileTag(final FileArgument fdesc)
{
- if (getName() == null && !fdesc.isShared) return null;
+ if (getName() == null && !fdesc.isShared)
+ {
+ return null;
+ }
if (fdesc.resource != null)
+ {
return fdesc.getNbtData(main);
+ }
if (parent == null)
+ {
return globalState;
- return ((CarpetScriptHost)parent).globalState;
+ }
+ return ((CarpetScriptHost) parent).globalState;
}
- public boolean writeTagFile(Tag tag, FileArgument fdesc)
+ public boolean writeTagFile(final Tag tag, final FileArgument fdesc)
{
- if (getName() == null && !fdesc.isShared) return false; // if belongs to an app, cannot be default host.
+ if (getName() == null && !fdesc.isShared)
+ {
+ return false; // if belongs to an app, cannot be default host.
+ }
if (fdesc.resource != null)
{
return fdesc.saveNbtData(main, tag);
}
- CarpetScriptHost responsibleHost = (parent != null)?(CarpetScriptHost) parent:this;
+ final CarpetScriptHost responsibleHost = (parent != null) ? (CarpetScriptHost) parent : this;
responsibleHost.globalState = tag;
if (responsibleHost.saveTimeout == 0)
{
@@ -934,48 +1034,42 @@ public class CarpetScriptHost extends ScriptHost
return true;
}
- public boolean removeResourceFile(FileArgument fdesc)
+ public boolean removeResourceFile(final FileArgument fdesc)
{
- if (getName() == null && !fdesc.isShared) return false; //
- return fdesc.dropExistingFile(main);
+ return (getName() != null || fdesc.isShared) && fdesc.dropExistingFile(main); //
}
- public boolean appendLogFile(FileArgument fdesc, List data)
+ public boolean appendLogFile(final FileArgument fdesc, final List data)
{
- if (getName() == null && !fdesc.isShared) return false; // if belongs to an app, cannot be default host.
- return fdesc.appendToTextFile(main, data);
+ return (getName() != null || fdesc.isShared) && fdesc.appendToTextFile(main, data); // if belongs to an app, cannot be default host.
}
- public List readTextResource(FileArgument fdesc)
+ public List readTextResource(final FileArgument fdesc)
{
- if (getName() == null && !fdesc.isShared) return null;
- return fdesc.listFile(main);
- }
-
- public JsonElement readJsonFile(FileArgument fdesc)
- {
- if (getName() == null && !fdesc.isShared) return null;
- return fdesc.readJsonFile(main);
+ return getName() == null && !fdesc.isShared ? null : fdesc.listFile(main);
}
- public Stream listFolder(FileArgument fdesc)
+ public JsonElement readJsonFile(final FileArgument fdesc)
{
- if (getName() == null && !fdesc.isShared) return null; //
- return fdesc.listFolder(main);
+ return getName() == null && !fdesc.isShared ? null : fdesc.readJsonFile(main);
}
- public boolean applyActionForResource(String path, boolean shared, Consumer action)
+ public Stream listFolder(final FileArgument fdesc)
{
- FileArgument fdesc = FileArgument.resourceFromPath(path, FileArgument.Reason.CREATE, shared);
+ return getName() == null && !fdesc.isShared ? null : fdesc.listFolder(main);
+ }
+
+ public boolean applyActionForResource(final String path, final boolean shared, final Consumer action)
+ {
+ final FileArgument fdesc = FileArgument.resourceFromPath(path, FileArgument.Reason.CREATE, shared);
return fdesc.findPathAndApply(main, action);
}
-
public void tick()
{
if (this.saveTimeout > 0)
{
- this.saveTimeout --;
+ this.saveTimeout--;
if (this.saveTimeout == 0)
{
dumpState();
@@ -983,7 +1077,7 @@ public class CarpetScriptHost extends ScriptHost
}
}
- public void setChatErrorSnooper(CommandSourceStack source)
+ public void setChatErrorSnooper(final CommandSourceStack source)
{
responsibleSource = source;
errorSnooper = (expr, /*Nullable*/ token, ctx, message) ->
@@ -992,15 +1086,15 @@ public class CarpetScriptHost extends ScriptHost
{
source.getPlayerOrException();
}
- catch (CommandSyntaxException e)
+ catch (final CommandSyntaxException e)
{
return null;
}
- String shebang = message+" in "+expr.getModuleName();
+ String shebang = message + " in " + expr.getModuleName();
if (token != null)
{
- String[] lines = expr.getCodeString().split("\n");
+ final String[] lines = expr.getCodeString().split("\n");
if (lines.length > 1)
{
@@ -1015,7 +1109,7 @@ public class CarpetScriptHost extends ScriptHost
{
Messenger.m(source, withLocals("l", lines[token.lineno - 1], ctx));
}
- Messenger.m(source, withLocals("l", lines[token.lineno].substring(0, token.linepos), ctx), "r HERE>> ",
+ Messenger.m(source, withLocals("l", lines[token.lineno].substring(0, token.linepos), ctx), "r HERE>> ",
withLocals("l", lines[token.lineno].substring(token.linepos), ctx));
if (lines.length > 1 && token.lineno < lines.length - 1)
{
@@ -1032,56 +1126,62 @@ public class CarpetScriptHost extends ScriptHost
/**
* Creates a {@link Component} using {@link Messenger} that has the locals in the {@code line} snippet with a hover over
- * tooltip with the value of the local at that location
- * @param line The line to find references to locals on
+ * tooltip with the value of the local at that location
+ *
+ * @param line The line to find references to locals on
* @param context The {@link Context} to extract the locals from
- * @param format The format to apply to each part of the line, without the trailing space
+ * @param format The format to apply to each part of the line, without the trailing space
* @return A BaseText of the given line with the given format, that is visibly the same as passing those to Messenger, but with references to the
- * locals in the {@link Context} with a hover over tooltip text
+ * locals in the {@link Context} with a hover over tooltip text
* @implNote The implementation of this method is far from perfect, and won't detect actual references to variables, but try to find the strings
- * and add the hover effect to anything that equals to any variable name, so short variable names may appear on random positions
+ * and add the hover effect to anything that equals to any variable name, so short variable names may appear on random positions
*/
- private static Component withLocals(String format, String line, Context context)
+ private static Component withLocals(String format, final String line, final Context context)
{
format += " ";
- List stringsToFormat = new ArrayList<>();
- TreeMap posToLocal = new TreeMap<>(); //Holds whether a local variable name is found at a specific index
- for (String local: context.variables.keySet())
+ final List stringsToFormat = new ArrayList<>();
+ final TreeMap posToLocal = new TreeMap<>(); //Holds whether a local variable name is found at a specific index
+ for (final String local : context.variables.keySet())
{
int pos = line.indexOf(local);
while (pos != -1)
{
posToLocal.merge(pos, local, (existingLocal, newLocal) ->
{
- if (newLocal.length() > existingLocal.length()) // Prefer longer variable names at the same position, since else single chars everywhere
- return local;
- else
- return existingLocal;
+ // Prefer longer variable names at the same position, since else single chars everywhere
+ return newLocal.length() > existingLocal.length() ? local : existingLocal;
});
pos = line.indexOf(local, pos + 1);
}
}
int lastPos = 0;
- for (Entry foundLocal : posToLocal.entrySet())
+ for (final Entry foundLocal : posToLocal.entrySet())
{
if (foundLocal.getKey() < lastPos) // system isn't perfect: part of another local
+ {
continue;
+ }
stringsToFormat.add(format + line.substring(lastPos, foundLocal.getKey()));
stringsToFormat.add(format + foundLocal.getValue());
- Value val = context.variables.get(foundLocal.getValue()).evalValue(context);
- String type = val.getTypeString();
+ final Value val = context.variables.get(foundLocal.getValue()).evalValue(context);
+ final String type = val.getTypeString();
String value;
- try {
+ try
+ {
value = val.getPrettyString();
- } catch (StackOverflowError e) {
+ }
+ catch (final StackOverflowError e)
+ {
value = "Exception while rendering variable, there seems to be a recursive reference in there";
}
stringsToFormat.add("^ Value of '" + foundLocal.getValue() + "' at position (" + type + "): \n"
- + value);
+ + value);
lastPos = foundLocal.getKey() + foundLocal.getValue().length();
}
if (line.length() != lastPos)
- stringsToFormat.add(format + line.substring(lastPos, line.length()));
+ {
+ stringsToFormat.add(format + line.substring(lastPos));
+ }
return Messenger.c(stringsToFormat.toArray());
}
@@ -1092,22 +1192,25 @@ public class CarpetScriptHost extends ScriptHost
super.resetErrorSnooper();
}
- public void handleErrorWithStack(String intro, Throwable exception)
+ public void handleErrorWithStack(final String intro, final Throwable exception)
{
if (responsibleSource != null)
{
- if (exception instanceof CarpetExpressionException) ((CarpetExpressionException) exception).printStack(responsibleSource);
- String message = exception.getMessage();
- Messenger.m(responsibleSource, "r "+intro+( (message == null || message.isEmpty())?"":": "+message));
+ if (exception instanceof final CarpetExpressionException cee)
+ {
+ cee.printStack(responsibleSource);
+ }
+ final String message = exception.getMessage();
+ Messenger.m(responsibleSource, "r " + intro + ((message == null || message.isEmpty()) ? "" : ": " + message));
}
else
{
- CarpetSettings.LOG.error(intro+": "+exception.getMessage());
+ CarpetSettings.LOG.error(intro + ": " + exception.getMessage());
}
}
@Override
- synchronized public void handleExpressionException(String message, ExpressionException exc)
+ public synchronized void handleExpressionException(final String message, final ExpressionException exc)
{
handleErrorWithStack(message, new CarpetExpressionException(exc.getMessage(), exc.stack));
}
@@ -1120,19 +1223,19 @@ public class CarpetScriptHost extends ScriptHost
{
return scriptServer();
}
-
+
@Override
public CarpetScriptServer scriptServer()
{
- return (CarpetScriptServer)super.scriptServer();
+ return (CarpetScriptServer) super.scriptServer();
}
@Override
- public boolean issueDeprecation(String feature)
+ public boolean issueDeprecation(final String feature)
{
- if(super.issueDeprecation(feature))
+ if (super.issueDeprecation(feature))
{
- Messenger.m(responsibleSource, "rb '"+feature+"' is deprecated and soon will be removed. Please consult the docs for their replacement");
+ Messenger.m(responsibleSource, "rb '" + feature + "' is deprecated and soon will be removed. Please consult the docs for their replacement");
return true;
}
return false;
diff --git a/src/main/java/carpet/script/CarpetScriptServer.java b/src/main/java/carpet/script/CarpetScriptServer.java
index 4ddf57a4..9ae29a2c 100644
--- a/src/main/java/carpet/script/CarpetScriptServer.java
+++ b/src/main/java/carpet/script/CarpetScriptServer.java
@@ -59,35 +59,38 @@ public class CarpetScriptServer extends ScriptServer
//make static for now, but will change that later:
public static final Logger LOG = LoggerFactory.getLogger("Scarpet");
public final MinecraftServer server;
- public CarpetScriptHost globalHost;
- public Map modules;
- public Set unloadableModules;
+ public CarpetScriptHost globalHost;
+ public Map modules;
+ public Set unloadableModules;
public long tickStart;
public boolean stopAll;
public int tickDepth;
- private Set holyMoly;
- public CarpetEventServer events;
+ private Set holyMoly;
+ public CarpetEventServer events;
private static final List bundledModuleData = new ArrayList<>();
private static final List ruleModuleData = new ArrayList<>();
+
/**
* Registers a Scarpet App to be always available under the {@code /script load} list.
- * @see Module#fromJarPath(String, String, boolean)
- *
+ *
* @param app The {@link Module} of the app
+ * @see Module#fromJarPath(String, String, boolean)
*/
- public static void registerBuiltInApp(Module app) {
+ public static void registerBuiltInApp(final Module app)
+ {
bundledModuleData.add(app);
}
/**
* Registers a Scarpet App to be used as a Rule App (to be controlled with the value of a Carpet rule).
* Libraries should be registered with {@link #registerBuiltInScript(BundledModule)} instead
- * @see Module#fromJarPath(String, String, boolean)
- *
+ *
* @param app The {@link Module} of the app.
+ * @see Module#fromJarPath(String, String, boolean)
*/
- public static void registerSettingsApp(Module app) {
+ public static void registerSettingsApp(final Module app)
+ {
ruleModuleData.add(app);
}
@@ -105,7 +108,7 @@ public class CarpetScriptServer extends ScriptServer
registerBuiltInApp(Module.carpetNative("distance_beta", false));
}
- public CarpetScriptServer(MinecraftServer server)
+ public CarpetScriptServer(final MinecraftServer server)
{
this.server = server;
init();
@@ -126,13 +129,14 @@ public class CarpetScriptServer extends ScriptServer
{
CarpetServer.settingsManager.initializeScarpetRules();
CarpetServer.extensions.forEach(e -> {
- if (e.extensionSettingsManager() != null) {
+ if (e.extensionSettingsManager() != null)
+ {
e.extensionSettingsManager().initializeScarpetRules();
}
});
if (CarpetSettings.scriptsAutoload)
{
- for (String moduleName: listAvailableModules(false))
+ for (final String moduleName : listAvailableModules(false))
{
addScriptHost(server.createCommandSourceStack(), moduleName, null, true, true, false, null);
}
@@ -140,40 +144,53 @@ public class CarpetScriptServer extends ScriptServer
CarpetEventServer.Event.START.onTick();
}
- public Module getModule(String name, boolean allowLibraries)
+ public Module getModule(final String name, final boolean allowLibraries)
{
- try {
- Path folder = server.getWorldPath(LevelResource.ROOT).resolve("scripts");
- if (!Files.exists(folder))
+ try
+ {
+ final Path folder = server.getWorldPath(LevelResource.ROOT).resolve("scripts");
+ if (!Files.exists(folder))
+ {
Files.createDirectories(folder);
- try (Stream folderLister = Files.list(folder)) {
- Optional scriptPath = folderLister
- .filter(script ->
- script.getFileName().toString().equalsIgnoreCase(name + ".sc") ||
- (allowLibraries && script.getFileName().toString().equalsIgnoreCase(name+".scl"))
- ).findFirst();
+ }
+ try (final Stream folderLister = Files.list(folder))
+ {
+ final Optional scriptPath = folderLister
+ .filter(script ->
+ script.getFileName().toString().equalsIgnoreCase(name + ".sc") ||
+ (allowLibraries && script.getFileName().toString().equalsIgnoreCase(name + ".scl"))
+ ).findFirst();
if (scriptPath.isPresent())
+ {
return Module.fromPath(scriptPath.get());
+ }
}
if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT)
{
- Path globalFolder = FabricLoader.getInstance().getConfigDir().resolve("carpet/scripts");
- if (!Files.exists(globalFolder))
+ final Path globalFolder = FabricLoader.getInstance().getConfigDir().resolve("carpet/scripts");
+ if (!Files.exists(globalFolder))
+ {
Files.createDirectories(globalFolder);
- try (Stream folderWalker = Files.walk(globalFolder)) {
- Optional scriptPath = folderWalker
+ }
+ try (final Stream folderWalker = Files.walk(globalFolder))
+ {
+ final Optional scriptPath = folderWalker
.filter(script -> script.getFileName().toString().equalsIgnoreCase(name + ".sc") ||
(allowLibraries && script.getFileName().toString().equalsIgnoreCase(name + ".scl")))
.findFirst();
if (scriptPath.isPresent())
+ {
return Module.fromPath(scriptPath.get());
+ }
}
}
- } catch (IOException e) {
+ }
+ catch (final IOException e)
+ {
CarpetSettings.LOG.error("Exception while loading the app: ", e);
}
- for (Module moduleData : bundledModuleData)
+ for (final Module moduleData : bundledModuleData)
{
if (moduleData.name().equalsIgnoreCase(name) && (allowLibraries || !moduleData.library()))
{
@@ -182,10 +199,10 @@ public class CarpetScriptServer extends ScriptServer
}
return null;
}
-
- public Module getRuleModule(String name)
+
+ public Module getRuleModule(final String name)
{
- for (Module moduleData : ruleModuleData)
+ for (final Module moduleData : ruleModuleData)
{
if (moduleData.name().equalsIgnoreCase(name))
{
@@ -195,101 +212,116 @@ public class CarpetScriptServer extends ScriptServer
return null;
}
- public List listAvailableModules(boolean includeBuiltIns)
+ public List listAvailableModules(final boolean includeBuiltIns)
{
- List moduleNames = new ArrayList<>();
+ final List moduleNames = new ArrayList<>();
if (includeBuiltIns)
{
- for (Module mi : bundledModuleData)
+ for (final Module mi : bundledModuleData)
{
- if (!mi.library() && !mi.name().endsWith("_beta")) moduleNames.add(mi.name());
+ if (!mi.library() && !mi.name().endsWith("_beta"))
+ {
+ moduleNames.add(mi.name());
+ }
}
}
- try {
- Path worldScripts = server.getWorldPath(LevelResource.ROOT).resolve("scripts");
- if (!Files.exists(worldScripts))
+ try
+ {
+ final Path worldScripts = server.getWorldPath(LevelResource.ROOT).resolve("scripts");
+ if (!Files.exists(worldScripts))
+ {
Files.createDirectories(worldScripts);
- try (Stream folderLister = Files.list(worldScripts)) {
+ }
+ try (final Stream folderLister = Files.list(worldScripts))
+ {
folderLister
- .filter(f -> f.toString().endsWith(".sc"))
- .forEach(f -> moduleNames.add(f.getFileName().toString().replaceFirst("\\.sc$","").toLowerCase(Locale.ROOT)));
+ .filter(f -> f.toString().endsWith(".sc"))
+ .forEach(f -> moduleNames.add(f.getFileName().toString().replaceFirst("\\.sc$", "").toLowerCase(Locale.ROOT)));
}
if (includeBuiltIns && (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT))
{
- Path globalScripts = FabricLoader.getInstance().getConfigDir().resolve("carpet/scripts");
+ final Path globalScripts = FabricLoader.getInstance().getConfigDir().resolve("carpet/scripts");
if (!Files.exists(globalScripts))
+ {
Files.createDirectories(globalScripts);
- try (Stream folderWalker = Files.walk(globalScripts, FileVisitOption.FOLLOW_LINKS)) {
+ }
+ try (final Stream folderWalker = Files.walk(globalScripts, FileVisitOption.FOLLOW_LINKS))
+ {
folderWalker
- .filter(f -> f.toString().endsWith(".sc"))
- .forEach(f -> moduleNames.add(f.getFileName().toString().replaceFirst("\\.sc$","").toLowerCase(Locale.ROOT)));
+ .filter(f -> f.toString().endsWith(".sc"))
+ .forEach(f -> moduleNames.add(f.getFileName().toString().replaceFirst("\\.sc$", "").toLowerCase(Locale.ROOT)));
}
}
- } catch (IOException e) {
+ }
+ catch (final IOException e)
+ {
CarpetSettings.LOG.error("Exception while searching for apps: ", e);
}
return moduleNames;
}
- public CarpetScriptHost getAppHostByName(String name)
+ public CarpetScriptHost getAppHostByName(final String name)
{
- if (name == null)
- return globalHost;
- return modules.get(name);
+ return name == null ? globalHost : modules.get(name);
}
- public boolean addScriptHost(CommandSourceStack source, String name, Predicate commandValidator,
- boolean perPlayer, boolean autoload, boolean isRuleApp, AppStoreManager.StoreNode installer)
+ public boolean addScriptHost(final CommandSourceStack source, String name, Predicate commandValidator,
+ final boolean perPlayer, final boolean autoload, final boolean isRuleApp, final AppStoreManager.StoreNode installer)
{
- CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet load", CarpetProfiler.TYPE.GENERAL);
- if (commandValidator == null) commandValidator = p -> true;
- long start = System.nanoTime();
+ final CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet load", CarpetProfiler.TYPE.GENERAL);
+ if (commandValidator == null)
+ {
+ commandValidator = p -> true;
+ }
+ final long start = System.nanoTime();
name = name.toLowerCase(Locale.ROOT);
boolean reload = false;
if (modules.containsKey(name))
{
- if (isRuleApp) return false;
+ if (isRuleApp)
+ {
+ return false;
+ }
removeScriptHost(source, name, false, isRuleApp);
reload = true;
}
- Module module = isRuleApp ? getRuleModule(name) : getModule(name, false);
+ final Module module = isRuleApp ? getRuleModule(name) : getModule(name, false);
if (module == null)
{
- Messenger.m(source, "r Failed to add "+name+" app: App not found");
+ Messenger.m(source, "r Failed to add " + name + " app: App not found");
return false;
}
- CarpetScriptHost newHost;
+ final CarpetScriptHost newHost;
try
{
newHost = CarpetScriptHost.create(this, module, perPlayer, source, commandValidator, isRuleApp, installer);
}
- catch (LoadException e)
+ catch (final LoadException e)
{
Messenger.m(source, "r Failed to add " + name + " app" + (e.getMessage() == null ? "" : ": " + e.getMessage()));
return false;
}
- // config needs to be read as we load the app since some events use that info
- //if (!newHost.readConfig())
- //{
- // Messenger.m(source, "r Failed to add "+name+" app: invalid app config (via '__config()' function)");
- // return false;
- //}
modules.put(name, newHost);
- if (!isRuleApp) unloadableModules.add(name);
+ if (!isRuleApp)
+ {
+ unloadableModules.add(name);
+ }
if (autoload && !newHost.persistenceRequired)
{
removeScriptHost(source, name, false, false);
return false;
}
- //addEvents(source, name);
- String action = (installer!=null)?(reload?"reinstalled":"installed"):(reload?"reloaded":"loaded");
+ final String action = (installer != null) ? (reload ? "reinstalled" : "installed") : (reload ? "reloaded" : "loaded");
- String finalName = name;
- Boolean isCommandAdded = newHost.addAppCommands(s -> {
- if (!isRuleApp) Messenger.m(source, Messenger.c("r Failed to add app '" + finalName + "': ", s));
+ final String finalName = name;
+ final Boolean isCommandAdded = newHost.addAppCommands(s -> {
+ if (!isRuleApp)
+ {
+ Messenger.m(source, Messenger.c("r Failed to add app '" + finalName + "': ", s));
+ }
});
if (isCommandAdded == null) // error should be dispatched
{
@@ -299,17 +331,23 @@ public class CarpetScriptServer extends ScriptServer
else if (isCommandAdded)
{
CommandHelper.notifyPlayersCommandsChanged(server);
- if (!isRuleApp) Messenger.m(source, "gi "+name+" app "+action+" with /"+name+" command");
+ if (!isRuleApp)
+ {
+ Messenger.m(source, "gi " + name + " app " + action + " with /" + name + " command");
+ }
}
else
{
- if (!isRuleApp) Messenger.m(source, "gi "+name+" app "+action);
+ if (!isRuleApp)
+ {
+ Messenger.m(source, "gi " + name + " app " + action);
+ }
}
if (newHost.isPerUser())
{
// that will provide player hosts right at the startup
- for (ServerPlayer player : source.getServer().getPlayerList().getPlayers())
+ for (final ServerPlayer player : source.getServer().getPlayerList().getPlayers())
{
newHost.retrieveForExecution(player.createCommandSourceStack(), player);
}
@@ -317,59 +355,76 @@ public class CarpetScriptServer extends ScriptServer
else
{
// global app - calling start now.
- FunctionValue onStart = newHost.getFunction("__on_start");
- if (onStart != null) newHost.callNow(onStart, Collections.emptyList());
+ final FunctionValue onStart = newHost.getFunction("__on_start");
+ if (onStart != null)
+ {
+ newHost.callNow(onStart, Collections.emptyList());
+ }
}
CarpetProfiler.end_current_section(currentSection);
- long end = System.nanoTime();
- CarpetSettings.LOG.info("App "+name+" loaded in "+(end-start)/1000000+" ms");
+ final long end = System.nanoTime();
+ CarpetSettings.LOG.info("App " + name + " loaded in " + (end - start) / 1000000 + " ms");
return true;
}
- public boolean isInvalidCommandRoot(String appName)
+ public boolean isInvalidCommandRoot(final String appName)
{
return holyMoly.contains(appName);
}
- public boolean removeScriptHost(CommandSourceStack source, String name, boolean notifySource, boolean isRuleApp)
+ public boolean removeScriptHost(final CommandSourceStack source, String name, final boolean notifySource, final boolean isRuleApp)
{
name = name.toLowerCase(Locale.ROOT);
if (!modules.containsKey(name) || (!isRuleApp && !unloadableModules.contains(name)))
{
- if (notifySource) Messenger.m(source, "r No such app found: ", "wb " + name);
+ if (notifySource)
+ {
+ Messenger.m(source, "r No such app found: ", "wb " + name);
+ }
return false;
}
// stop all events associated with name
- CarpetScriptHost host = modules.remove(name);
+ final CarpetScriptHost host = modules.remove(name);
events.removeAllHostEvents(host);
host.onClose();
if (host.hasCommand)
- ((CommandDispatcherInterface)server.getCommands().getDispatcher()).carpet$unregister(name);
- if (!isRuleApp) unloadableModules.remove(name);
+ {
+ ((CommandDispatcherInterface) server.getCommands().getDispatcher()).carpet$unregister(name);
+ }
+ if (!isRuleApp)
+ {
+ unloadableModules.remove(name);
+ }
CommandHelper.notifyPlayersCommandsChanged(server);
- if (notifySource) Messenger.m(source, "gi Removed "+name+" app");
+ if (notifySource)
+ {
+ Messenger.m(source, "gi Removed " + name + " app");
+ }
return true;
}
- public boolean uninstallApp(CommandSourceStack source, String name)
+ public boolean uninstallApp(final CommandSourceStack source, String name)
{
try
{
name = name.toLowerCase(Locale.ROOT);
- Path folder = server.getWorldPath(LevelResource.ROOT).resolve("scripts/trash");
- if (!Files.exists(folder)) Files.createDirectories(folder);
- if (!Files.exists(folder.getParent().resolve(name+".sc")))
+ final Path folder = server.getWorldPath(LevelResource.ROOT).resolve("scripts/trash");
+ if (!Files.exists(folder))
+ {
+ Files.createDirectories(folder);
+ }
+ if (!Files.exists(folder.getParent().resolve(name + ".sc")))
{
Messenger.m(source, "App doesn't exist in the world scripts folder, so can only be unloaded");
return false;
}
removeScriptHost(source, name, false, false);
- Files.move(folder.getParent().resolve(name+".sc"), folder.resolve(name+".sc"), StandardCopyOption.REPLACE_EXISTING);
- Messenger.m(source, "gi Removed "+name+" app");
+ Files.move(folder.getParent().resolve(name + ".sc"), folder.resolve(name + ".sc"), StandardCopyOption.REPLACE_EXISTING);
+ Messenger.m(source, "gi Removed " + name + " app");
return true;
}
- catch (IOException exc)
+ catch (final IOException exc)
{
Messenger.m(source, "rb Failed to uninstall the app");
}
@@ -380,10 +435,13 @@ public class CarpetScriptServer extends ScriptServer
{
CarpetProfiler.ProfilerToken token;
token = CarpetProfiler.start_section(null, "Scarpet schedule", CarpetProfiler.TYPE.GENERAL);
- events.handleEvents.getWhileDisabled( () -> {events.tick(); return null;});
+ events.handleEvents.getWhileDisabled(() -> {
+ events.tick();
+ return null;
+ });
CarpetProfiler.end_current_section(token);
token = CarpetProfiler.start_section(null, "Scarpet app data", CarpetProfiler.TYPE.GENERAL);
- for (CarpetScriptHost host : modules.values())
+ for (final CarpetScriptHost host : modules.values())
{
host.tick();
}
@@ -393,14 +451,14 @@ public class CarpetScriptServer extends ScriptServer
public void onClose()
{
CarpetEventServer.Event.SHUTDOWN.onTick();
- for (CarpetScriptHost host : modules.values())
+ for (final CarpetScriptHost host : modules.values())
{
host.onClose();
events.removeAllHostEvents(host);
}
}
- public void onPlayerJoin(ServerPlayer player)
+ public void onPlayerJoin(final ServerPlayer player)
{
modules.values().forEach(h ->
{
@@ -410,36 +468,38 @@ public class CarpetScriptServer extends ScriptServer
{
h.retrieveOwnForExecution(player.createCommandSourceStack());
}
- catch (CommandSyntaxException ignored)
+ catch (final CommandSyntaxException ignored)
{
}
}
});
}
- private static record TransferData(boolean perUser, Predicate commandValidator, boolean isRuleApp)
+ private record TransferData(boolean perUser, Predicate commandValidator,
+ boolean isRuleApp)
{
- private TransferData(CarpetScriptHost host)
+ private TransferData(final CarpetScriptHost host)
{
this(host.perUser, host.commandValidator, host.isRuleApp);
}
}
- public void reload(MinecraftServer server)
+ public void reload(final MinecraftServer server)
{
- Map apps = new HashMap<>();
+ final Map apps = new HashMap<>();
modules.forEach((s, h) -> apps.put(s, new TransferData(h)));
apps.keySet().forEach(s -> removeScriptHost(server.createCommandSourceStack(), s, false, false));
CarpetEventServer.Event.clearAllBuiltinEvents();
init();
- apps.forEach((s, data) -> addScriptHost(server.createCommandSourceStack(), s,data.commandValidator, data.perUser,false, data.isRuleApp, null));
+ apps.forEach((s, data) -> addScriptHost(server.createCommandSourceStack(), s, data.commandValidator, data.perUser, false, data.isRuleApp, null));
}
public void reAddCommands()
{
- modules.values().forEach(host -> host.addAppCommands(s -> {}));
+ modules.values().forEach(host -> host.addAppCommands(s -> {
+ }));
}
-
+
public static void parseFunctionClasses()
{
ExpressionException.prepareForDoom(); // see fc-#1172
@@ -451,7 +511,7 @@ public class CarpetScriptServer extends ScriptServer
AnnotationParser.parseFunctionClass(Loops.class);
AnnotationParser.parseFunctionClass(Sys.class);
AnnotationParser.parseFunctionClass(Threading.class);
-
+
// API
AnnotationParser.parseFunctionClass(Auxiliary.class);
AnnotationParser.parseFunctionClass(BlockIterators.class);
diff --git a/src/main/java/carpet/script/Context.java b/src/main/java/carpet/script/Context.java
index 748da050..430159ca 100644
--- a/src/main/java/carpet/script/Context.java
+++ b/src/main/java/carpet/script/Context.java
@@ -13,6 +13,7 @@ public class Context
{
NONE, VOID, BOOLEAN, NUMBER, STRING, LIST, ITERATOR, SIGNATURE, LOCALIZATION, LVALUE, MAPDEF
}
+
public static final Type NONE = Type.NONE;
public static final Type VOID = Type.VOID;
public static final Type BOOLEAN = Type.BOOLEAN;
@@ -29,32 +30,32 @@ public class Context
public final ScriptHost host;
- public Context(ScriptHost host)
+ public Context(final ScriptHost host)
{
this.host = host;
}
- public LazyValue getVariable(String name)
+ public LazyValue getVariable(final String name)
{
return variables.get(name);
}
- public void setVariable(String name, LazyValue lv)
+ public void setVariable(final String name, final LazyValue lv)
{
variables.put(name, lv);
}
- public void delVariable(String variable)
+ public void delVariable(final String variable)
{
variables.remove(variable);
}
- public void removeVariablesMatching(String varname)
+ public void removeVariablesMatching(final String varname)
{
variables.entrySet().removeIf(e -> e.getKey().startsWith(varname));
}
- public Context with(String variable, LazyValue lv)
+ public Context with(final String variable, final LazyValue lv)
{
variables.put(variable, lv);
return this;
@@ -67,7 +68,7 @@ public class Context
public Context recreate()
{
- Context ctx = duplicate();
+ final Context ctx = duplicate();
ctx.initialize();
return ctx;
}
@@ -84,12 +85,12 @@ public class Context
{
return new Context(this.host);
}
+
public ScriptHost.ErrorSnooper getErrorSnooper()
{
return host.errorSnooper;
}
-
/**
* immutable context only for reason on reporting access violations in evaluating expressions in optimizization
* mode detecting any potential violations that may happen on the way
@@ -97,10 +98,11 @@ public class Context
public static class ContextForErrorReporting extends Context
{
public ScriptHost.ErrorSnooper optmizerEerrorSnooper;
- public ContextForErrorReporting(Context parent)
+
+ public ContextForErrorReporting(final Context parent)
{
super(null);
- optmizerEerrorSnooper = parent.host.errorSnooper;
+ optmizerEerrorSnooper = parent.host.errorSnooper;
}
@Override
@@ -116,31 +118,64 @@ public class Context
"of scarpet authors. Please report this issue directly to the scarpet issue tracker");
}
- @Override
- public LazyValue getVariable(String name) { badProgrammer(); return null;}
@Override
- public void setVariable(String name, LazyValue lv) { badProgrammer(); }
+ public LazyValue getVariable(final String name)
+ {
+ badProgrammer();
+ return null;
+ }
@Override
- public void delVariable(String variable) { badProgrammer(); }
+ public void setVariable(final String name, final LazyValue lv)
+ {
+ badProgrammer();
+ }
@Override
- public void removeVariablesMatching(String varname) { badProgrammer(); }
+ public void delVariable(final String variable)
+ {
+ badProgrammer();
+ }
@Override
- public Context with(String variable, LazyValue lv) { badProgrammer(); return this; }
+ public void removeVariablesMatching(final String varname)
+ {
+ badProgrammer();
+ }
@Override
- public Set getAllVariableNames() { badProgrammer(); return null;}
+ public Context with(final String variable, final LazyValue lv)
+ {
+ badProgrammer();
+ return this;
+ }
@Override
- public Context recreate() { badProgrammer(); return null;}
+ public Set getAllVariableNames()
+ {
+ badProgrammer();
+ return null;
+ }
@Override
- protected void initialize() { badProgrammer();}
+ public Context recreate()
+ {
+ badProgrammer();
+ return null;
+ }
@Override
- public Context duplicate() { badProgrammer(); return null;}
+ protected void initialize()
+ {
+ badProgrammer();
+ }
+
+ @Override
+ public Context duplicate()
+ {
+ badProgrammer();
+ return null;
+ }
}
}
diff --git a/src/main/java/carpet/script/EntityEventsGroup.java b/src/main/java/carpet/script/EntityEventsGroup.java
index a249f67c..41b1dc3e 100644
--- a/src/main/java/carpet/script/EntityEventsGroup.java
+++ b/src/main/java/carpet/script/EntityEventsGroup.java
@@ -8,72 +8,93 @@ import carpet.script.value.NumericValue;
import carpet.script.value.StringValue;
import carpet.script.value.Value;
import carpet.script.value.ValueConversions;
+
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.phys.Vec3;
public class EntityEventsGroup
{
- private static record EventKey(String host, String user) {}
+ private record EventKey(String host, String user)
+ {
+ }
+
private final Map> actions;
private final Entity entity;
- public EntityEventsGroup(Entity e)
+
+ public EntityEventsGroup(final Entity e)
{
actions = new HashMap<>();
entity = e;
}
- public void onEvent(Event type, Object... args)
+ public void onEvent(final Event type, final Object... args)
{
- if (actions.isEmpty()) return; // most of the cases, trying to be nice
- Map actionSet = actions.get(type);
- if (actionSet == null) return;
- if (CarpetServer.scriptServer == null) return; // executed after world is closin down
- for (Iterator> iterator = actionSet.entrySet().iterator(); iterator.hasNext(); )
+ if (actions.isEmpty())
{
- Map.Entry action = iterator.next();
- EventKey key = action.getKey();
- ScriptHost host = CarpetServer.scriptServer.getAppHostByName(key.host());
+ return; // most of the cases, trying to be nice
+ }
+ final Map actionSet = actions.get(type);
+ if (actionSet == null)
+ {
+ return;
+ }
+ if (CarpetServer.scriptServer == null)
+ {
+ return; // executed after world is closin down
+ }
+ for (final Iterator> iterator = actionSet.entrySet().iterator(); iterator.hasNext(); )
+ {
+ final Map.Entry action = iterator.next();
+ final EventKey key = action.getKey();
+ final ScriptHost host = CarpetServer.scriptServer.getAppHostByName(key.host());
if (host == null)
{
iterator.remove();
continue;
}
- if (key.user() != null)
+ if (key.user() != null && entity.getServer().getPlayerList().getPlayerByName(key.user()) == null)
{
- if (entity.getServer().getPlayerList().getPlayerByName(key.user())==null)
- {
- iterator.remove();
- continue;
- }
+ iterator.remove();
+ continue;
}
if (type.call(action.getValue(), entity, args) == CarpetEventServer.CallbackResult.FAIL)
+ {
iterator.remove();
+ }
+ }
+ if (actionSet.isEmpty())
+ {
+ actions.remove(type);
}
- if (actionSet.isEmpty()) actions.remove(type);
}
- public void addEvent(Event type, ScriptHost host, FunctionValue fun, List extraargs)
+ public void addEvent(final Event type, final ScriptHost host, final FunctionValue fun, final List extraargs)
{
- EventKey key = new EventKey(host.getName(), host.user);
+ final EventKey key = new EventKey(host.getName(), host.user);
if (fun != null)
{
- CarpetEventServer.Callback call = type.create(key, fun, extraargs);
+ final CarpetEventServer.Callback call = type.create(key, fun, extraargs);
if (call == null)
- throw new InternalExpressionException("wrong number of arguments for callback, required "+type.argcount);
+ {
+ throw new InternalExpressionException("wrong number of arguments for callback, required " + type.argcount);
+ }
actions.computeIfAbsent(type, k -> new HashMap<>()).put(key, call);
}
else
{
actions.computeIfAbsent(type, k -> new HashMap<>()).remove(key);
if (actions.get(type).isEmpty())
+ {
actions.remove(type);
+ }
}
}
@@ -84,11 +105,11 @@ public class EntityEventsGroup
public static final Event ON_DEATH = new Event("on_death", 1)
{
@Override
- public List makeArgs(Entity entity, Object... providedArgs)
+ public List makeArgs(final Entity entity, final Object... providedArgs)
{
return Arrays.asList(
new EntityValue(entity),
- new StringValue((String)providedArgs[0])
+ new StringValue((String) providedArgs[0])
);
}
};
@@ -97,22 +118,22 @@ public class EntityEventsGroup
public static final Event ON_DAMAGE = new Event("on_damaged", 3)
{
@Override
- public List makeArgs(Entity entity, Object... providedArgs)
+ public List makeArgs(final Entity entity, final Object... providedArgs)
{
- float amount = (Float)providedArgs[0];
- DamageSource source = (DamageSource)providedArgs[1];
+ final float amount = (Float) providedArgs[0];
+ final DamageSource source = (DamageSource) providedArgs[1];
return Arrays.asList(
new EntityValue(entity),
new NumericValue(amount),
new StringValue(source.getMsgId()),
- source.getEntity()==null?Value.NULL:new EntityValue(source.getEntity())
+ source.getEntity() == null ? Value.NULL : new EntityValue(source.getEntity())
);
}
};
public static final Event ON_MOVE = new Event("on_move", 3)
{
@Override
- public List makeArgs(Entity entity, Object... providedArgs)
+ public List makeArgs(final Entity entity, final Object... providedArgs)
{
return Arrays.asList(
new EntityValue(entity),
@@ -125,26 +146,30 @@ public class EntityEventsGroup
public final int argcount;
public final String id;
- public Event(String identifier, int args)
+
+ public Event(final String identifier, final int args)
{
id = identifier;
- argcount = args+1; // entity is not extra
+ argcount = args + 1; // entity is not extra
byName.put(identifier, this);
}
- public CarpetEventServer.Callback create(EventKey key, FunctionValue function, List extraArgs)
+
+ public CarpetEventServer.Callback create(final EventKey key, final FunctionValue function, final List extraArgs)
{
- if ((function.getArguments().size()-(extraArgs == null ? 0 : extraArgs.size())) != argcount)
+ if ((function.getArguments().size() - (extraArgs == null ? 0 : extraArgs.size())) != argcount)
{
return null;
}
return new CarpetEventServer.Callback(key.host(), key.user(), function, extraArgs);
}
- public CarpetEventServer.CallbackResult call(CarpetEventServer.Callback tickCall, Entity entity, Object ... args)
+
+ public CarpetEventServer.CallbackResult call(final CarpetEventServer.Callback tickCall, final Entity entity, final Object... args)
{
- assert args.length == argcount-1;
+ assert args.length == argcount - 1;
return tickCall.execute(entity.createCommandSourceStack(), makeArgs(entity, args));
}
- protected List makeArgs(Entity entity, Object ... args)
+
+ protected List makeArgs(final Entity entity, final Object... args)
{
return Collections.singletonList(new EntityValue(entity));
}
diff --git a/src/main/java/carpet/script/Expression.java b/src/main/java/carpet/script/Expression.java
index 90f493c2..c9aca6af 100644
--- a/src/main/java/carpet/script/Expression.java
+++ b/src/main/java/carpet/script/Expression.java
@@ -44,9 +44,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
-import java.util.function.BiFunction;
-import java.util.function.Function;
-import java.util.function.Supplier;
+import java.util.function.*;
import java.util.stream.Collectors;
import static java.lang.Math.max;
@@ -54,9 +52,15 @@ import static java.lang.Math.min;
public class Expression
{
- /** The current infix expression */
+ /**
+ * The current infix expression
+ */
private String expression;
- String getCodeString() {return expression;}
+
+ String getCodeString()
+ {
+ return expression;
+ }
private boolean allowNewlineSubstitutions = true;
private boolean allowComments = false;
@@ -74,23 +78,36 @@ public class Expression
allowComments = true;
}
- public void asAModule(Module mi)
+ public void asAModule(final Module mi)
{
module = mi;
}
- /** Cached AST (Abstract Syntax Tree) (root) of the expression */
+ /**
+ * Cached AST (Abstract Syntax Tree) (root) of the expression
+ */
private LazyValue ast = null;
- /** script specific operatos and built-in functions */
+ /**
+ * script specific operatos and built-in functions
+ */
private final Map operators = new Object2ObjectOpenHashMap<>();
- public boolean isAnOperator(String opname) { return operators.containsKey(opname) || operators.containsKey(opname+"u");}
- private final Map functions = new Object2ObjectOpenHashMap<>();
- public Set getFunctionNames() {return functions.keySet();}
+ public boolean isAnOperator(final String opname)
+ {
+ return operators.containsKey(opname) || operators.containsKey(opname + "u");
+ }
+
+ private final Map functions = new Object2ObjectOpenHashMap<>();
+
+ public Set getFunctionNames()
+ {
+ return functions.keySet();
+ }
private final Map functionalEquivalence = new Object2ObjectOpenHashMap<>();
- public void addFunctionalEquivalence(String operator, String function)
+
+ public void addFunctionalEquivalence(final String operator, final String function)
{
assert operators.containsKey(operator);
assert functions.containsKey(function);
@@ -105,27 +122,30 @@ public class Expression
"false", Value.FALSE
);
- protected Value getConstantFor(String surface)
+ protected Value getConstantFor(final String surface)
{
return constants.get(surface);
}
- public List getExpressionSnippet(Tokenizer.Token token)
+ public List getExpressionSnippet(final Tokenizer.Token token)
{
- String code = this.getCodeString();
- List output = new ArrayList<>(getExpressionSnippetLeftContext(token, code, 1));
- List context = getExpressionSnippetContext(token, code);
- output.add(context.get(0)+" HERE>> "+context.get(1));
+ final String code = this.getCodeString();
+ final List output = new ArrayList<>(getExpressionSnippetLeftContext(token, code, 1));
+ final List context = getExpressionSnippetContext(token, code);
+ output.add(context.get(0) + " HERE>> " + context.get(1));
output.addAll(getExpressionSnippetRightContext(token, code, 1));
return output;
}
- private static List getExpressionSnippetLeftContext(Tokenizer.Token token, String expr, int contextsize)
+ private static List getExpressionSnippetLeftContext(final Tokenizer.Token token, final String expr, final int contextsize)
{
- List output = new ArrayList<>();
- String[] lines = expr.split("\n");
- if (lines.length == 1) return output;
- for (int lno=token.lineno-1; lno >=0 && output.size() < contextsize; lno-- )
+ final List output = new ArrayList<>();
+ final String[] lines = expr.split("\n");
+ if (lines.length == 1)
+ {
+ return output;
+ }
+ for (int lno = token.lineno - 1; lno >= 0 && output.size() < contextsize; lno--)
{
output.add(lines[lno]);
}
@@ -133,10 +153,10 @@ public class Expression
return output;
}
- private static List getExpressionSnippetContext(Tokenizer.Token token, String expr)
+ private static List getExpressionSnippetContext(final Tokenizer.Token token, final String expr)
{
- List output = new ArrayList<>();
- String[] lines = expr.split("\n");
+ final List output = new ArrayList<>();
+ final String[] lines = expr.split("\n");
if (lines.length > 1)
{
output.add(lines[token.lineno].substring(0, token.linepos));
@@ -144,18 +164,21 @@ public class Expression
}
else
{
- output.add( expr.substring(max(0, token.pos-40), token.pos));
- output.add( expr.substring(token.pos, min(token.pos+1+40, expr.length())));
+ output.add(expr.substring(max(0, token.pos - 40), token.pos));
+ output.add(expr.substring(token.pos, min(token.pos + 1 + 40, expr.length())));
}
return output;
}
- private static List getExpressionSnippetRightContext(Tokenizer.Token token, String expr, int contextsize)
+ private static List getExpressionSnippetRightContext(final Tokenizer.Token token, final String expr, final int contextsize)
{
- List output = new ArrayList<>();
- String[] lines = expr.split("\n");
- if (lines.length == 1) { return output; }
- for (int lno=token.lineno+1; lno < lines.length && output.size() < contextsize; lno++ )
+ final List output = new ArrayList<>();
+ final String[] lines = expr.split("\n");
+ if (lines.length == 1)
+ {
+ return output;
+ }
+ for (int lno = token.lineno + 1; lno < lines.length && output.size() < contextsize; lno++)
{
output.add(lines[lno]);
}
@@ -163,34 +186,37 @@ public class Expression
}
- public void addLazyUnaryOperator(String surface, int precedence, boolean leftAssoc, boolean pure, Function staticTyper,
- TriFunction lazyfun)
+ public void addLazyUnaryOperator(final String surface, final int precedence, final boolean leftAssoc, final boolean pure, final Function staticTyper,
+ final TriFunction lazyfun)
{
- operators.put(surface+"u", new AbstractLazyOperator(precedence, leftAssoc)
+ operators.put(surface + "u", new AbstractLazyOperator(precedence, leftAssoc)
{
@Override
- public boolean pure() {
+ public boolean pure()
+ {
return pure;
}
@Override
- public boolean transitive() {
+ public boolean transitive()
+ {
return false;
}
@Override
- public Context.Type staticType(Context.Type outerType) {
+ public Context.Type staticType(final Context.Type outerType)
+ {
return staticTyper.apply(outerType);
}
@Override
- public LazyValue lazyEval(Context c, Context.Type t, Expression e, Tokenizer.Token token, LazyValue v, LazyValue v2)
+ public LazyValue lazyEval(final Context c, final Context.Type t, final Expression e, final Tokenizer.Token token, final LazyValue v, final LazyValue v2)
{
try
{
return lazyfun.apply(c, t, v);
}
- catch (RuntimeException exc)
+ catch (final RuntimeException exc)
{
throw handleCodeException(c, exc, e, token);
}
@@ -199,29 +225,31 @@ public class Expression
}
- public void addLazyBinaryOperatorWithDelegation(String surface, int precedence, boolean leftAssoc, boolean pure,
- SexFunction lazyfun)
+ public void addLazyBinaryOperatorWithDelegation(final String surface, final int precedence, final boolean leftAssoc, final boolean pure,
+ final SexFunction lazyfun)
{
operators.put(surface, new AbstractLazyOperator(precedence, leftAssoc)
{
@Override
- public boolean pure() {
+ public boolean pure()
+ {
return pure;
}
@Override
- public boolean transitive() {
+ public boolean transitive()
+ {
return false;
}
@Override
- public LazyValue lazyEval(Context c, Context.Type type, Expression e, Tokenizer.Token t, LazyValue v1, LazyValue v2)
+ public LazyValue lazyEval(final Context c, final Context.Type type, final Expression e, final Tokenizer.Token t, final LazyValue v1, final LazyValue v2)
{
try
{
return lazyfun.apply(c, type, e, t, v1, v2);
}
- catch (RuntimeException exc)
+ catch (final RuntimeException exc)
{
throw handleCodeException(c, exc, e, t);
}
@@ -229,35 +257,37 @@ public class Expression
});
}
- public void addCustomFunction(String name, ILazyFunction fun)
+ public void addCustomFunction(final String name, final ILazyFunction fun)
{
functions.put(name, fun);
}
- public void addLazyFunctionWithDelegation(String name, int numpar, boolean pure, boolean transitive,
- QuinnFunction, LazyValue> lazyfun)
+ public void addLazyFunctionWithDelegation(final String name, final int numpar, final boolean pure, final boolean transitive,
+ final QuinnFunction, LazyValue> lazyfun)
{
functions.put(name, new AbstractLazyFunction(numpar, name)
{
@Override
- public boolean pure() {
+ public boolean pure()
+ {
return pure;
}
@Override
- public boolean transitive() {
+ public boolean transitive()
+ {
return transitive;
}
@Override
- public LazyValue lazyEval(Context c, Context.Type type, Expression e, Tokenizer.Token t, List lv)
+ public LazyValue lazyEval(final Context c, final Context.Type type, final Expression e, final Tokenizer.Token t, final List lv)
{
ILazyFunction.checkInterrupts();
try
{
return lazyfun.apply(c, type, e, t, lv);
}
- catch (RuntimeException exc)
+ catch (final RuntimeException exc)
{
throw handleCodeException(c, exc, e, t);
}
@@ -265,30 +295,32 @@ public class Expression
});
}
- public void addFunctionWithDelegation(String name, int numpar, boolean pure, boolean transitive,
- QuinnFunction, Value> fun)
+ public void addFunctionWithDelegation(final String name, final int numpar, final boolean pure, final boolean transitive,
+ final QuinnFunction, Value> fun)
{
functions.put(name, new AbstractLazyFunction(numpar, name)
{
@Override
- public boolean pure() {
+ public boolean pure()
+ {
return pure;
}
@Override
- public boolean transitive() {
+ public boolean transitive()
+ {
return transitive;
}
@Override
- public LazyValue lazyEval(Context c, Context.Type type, Expression e, Tokenizer.Token t, List lv)
+ public LazyValue lazyEval(final Context c, final Context.Type type, final Expression e, final Tokenizer.Token t, final List lv)
{
try
{
- Value res = fun.apply(c, type, e, t, unpackArgs(lv, c, Context.NONE));
+ final Value res = fun.apply(c, type, e, t, unpackArgs(lv, c, Context.NONE));
return (cc, tt) -> res;
}
- catch (RuntimeException exc)
+ catch (final RuntimeException exc)
{
throw handleCodeException(c, exc, e, t);
}
@@ -296,37 +328,39 @@ public class Expression
});
}
- public void addLazyBinaryOperator(String surface, int precedence, boolean leftAssoc, boolean pure, Function typer,
- QuadFunction lazyfun)
+ public void addLazyBinaryOperator(final String surface, final int precedence, final boolean leftAssoc, final boolean pure, final Function typer,
+ final QuadFunction lazyfun)
{
operators.put(surface, new AbstractLazyOperator(precedence, leftAssoc)
{
@Override
- public boolean pure() {
+ public boolean pure()
+ {
return pure;
}
@Override
- public boolean transitive() {
+ public boolean transitive()
+ {
return false;
}
@Override
- public Context.Type staticType(Context.Type outerType)
+ public Context.Type staticType(final Context.Type outerType)
{
return typer.apply(outerType);
}
@Override
- public LazyValue lazyEval(Context c, Context.Type t, Expression e, Tokenizer.Token token, LazyValue v1, LazyValue v2)
+ public LazyValue lazyEval(final Context c, final Context.Type t, final Expression e, final Tokenizer.Token token, final LazyValue v1, final LazyValue v2)
{
ILazyFunction.checkInterrupts();
try
{
return lazyfun.apply(c, t, v1, v2);
}
- catch (RuntimeException exc)
+ catch (final RuntimeException exc)
{
throw handleCodeException(c, exc, e, token);
}
@@ -334,30 +368,32 @@ public class Expression
});
}
- public void addBinaryContextOperator(String surface, int precedence, boolean leftAssoc, boolean pure, boolean transitive,
- QuadFunction fun)
+ public void addBinaryContextOperator(final String surface, final int precedence, final boolean leftAssoc, final boolean pure, final boolean transitive,
+ final QuadFunction fun)
{
operators.put(surface, new AbstractLazyOperator(precedence, leftAssoc)
{
@Override
- public boolean pure() {
+ public boolean pure()
+ {
return pure;
}
@Override
- public boolean transitive() {
+ public boolean transitive()
+ {
return transitive;
}
@Override
- public LazyValue lazyEval(Context c, Context.Type t, Expression e, Tokenizer.Token token, LazyValue v1, LazyValue v2)
+ public LazyValue lazyEval(final Context c, final Context.Type t, final Expression e, final Tokenizer.Token token, final LazyValue v1, final LazyValue v2)
{
try
{
- Value ret = fun.apply(c, t, v1.evalValue(c, Context.NONE), v2.evalValue(c, Context.NONE));
+ final Value ret = fun.apply(c, t, v1.evalValue(c, Context.NONE), v2.evalValue(c, Context.NONE));
return (cc, tt) -> ret;
}
- catch (RuntimeException exc)
+ catch (final RuntimeException exc)
{
throw handleCodeException(c, exc, e, token);
}
@@ -365,144 +401,176 @@ public class Expression
});
}
- public static RuntimeException handleCodeException(Context c, RuntimeException exc, Expression e, Tokenizer.Token token)
+ public static RuntimeException handleCodeException(final Context c, final RuntimeException exc, final Expression e, final Tokenizer.Token token)
{
if (exc instanceof ExitStatement)
+ {
return exc;
+ }
if (exc instanceof IntegrityException)
+ {
return exc;
- if (exc instanceof InternalExpressionException)
- return ((InternalExpressionException) exc).promote(c, e, token);
+ }
+ if (exc instanceof final InternalExpressionException iee)
+ {
+ return iee.promote(c, e, token);
+ }
if (exc instanceof ArithmeticException)
- return new ExpressionException(c, e, token, "Your math is wrong, "+exc.getMessage());
+ {
+ return new ExpressionException(c, e, token, "Your math is wrong, " + exc.getMessage());
+ }
if (exc instanceof ResolvedException)
+ {
return exc;
+ }
// unexpected really - should be caught earlier and converted to InternalExpressionException
CarpetSettings.LOG.error("Unexpected exception while running Scarpet code", exc);
return new ExpressionException(c, e, token, "Internal error (please report this issue to Carpet) while evaluating: " + exc);
}
- public void addUnaryOperator(String surface, boolean leftAssoc, Function fun)
+ public void addUnaryOperator(final String surface, final boolean leftAssoc, final Function fun)
{
- operators.put(surface+"u", new AbstractUnaryOperator(Operators.precedence.get("unary+-!..."), leftAssoc)
+ operators.put(surface + "u", new AbstractUnaryOperator(Operators.precedence.get("unary+-!..."), leftAssoc)
{
@Override
- public Value evalUnary(Value v1)
+ public Value evalUnary(final Value v1)
{
return fun.apply(v1);
}
});
}
- public void addBinaryOperator(String surface, int precedence, boolean leftAssoc, BiFunction fun)
+ public void addBinaryOperator(final String surface, final int precedence, final boolean leftAssoc, final BiFunction fun)
{
operators.put(surface, new AbstractOperator(precedence, leftAssoc)
{
@Override
- public Value eval(Value v1, Value v2) { return fun.apply(v1, v2); }
+ public Value eval(final Value v1, final Value v2)
+ {
+ return fun.apply(v1, v2);
+ }
});
}
- public void addUnaryFunction(String name, Function fun)
+ public void addUnaryFunction(final String name, final Function fun)
{
- functions.put(name, new AbstractFunction(1, name)
+ functions.put(name, new AbstractFunction(1, name)
{
@Override
- public Value eval(List parameters) { return fun.apply(parameters.get(0)); }
+ public Value eval(final List parameters)
+ {
+ return fun.apply(parameters.get(0));
+ }
});
}
- public void addImpureUnaryFunction(String name, Function fun)
+ public void addImpureUnaryFunction(final String name, final Function fun)
{
- functions.put(name, new AbstractFunction(1, name)
+ functions.put(name, new AbstractFunction(1, name)
{
@Override
- public boolean pure() {
+ public boolean pure()
+ {
return false;
}
@Override
- public Value eval(List parameters) { return fun.apply(parameters.get(0)); }
+ public Value eval(final List parameters)
+ {
+ return fun.apply(parameters.get(0));
+ }
});
}
- public void addBinaryFunction(String name, BiFunction fun)
+ public void addBinaryFunction(final String name, final BiFunction fun)
{
functions.put(name, new AbstractFunction(2, name)
{
@Override
- public Value eval(List parameters) { return fun.apply(parameters.get(0), parameters.get(1)); }
+ public Value eval(final List parameters)
+ {
+ return fun.apply(parameters.get(0), parameters.get(1));
+ }
});
}
- public void addFunction(String name, Function, Value> fun)
+ public void addFunction(final String name, final Function, Value> fun)
{
functions.put(name, new AbstractFunction(-1, name)
{
@Override
- public Value eval(List parameters) { return fun.apply(parameters); }
+ public Value eval(final List parameters)
+ {
+ return fun.apply(parameters);
+ }
});
}
- public void addImpureFunction(String name, Function, Value> fun)
+ public void addImpureFunction(final String name, final Function, Value> fun)
{
functions.put(name, new AbstractFunction(-1, name)
{
@Override
- public boolean pure() {
+ public boolean pure()
+ {
return false;
}
@Override
- public Value eval(List parameters) { return fun.apply(parameters); }
+ public Value eval(final List parameters)
+ {
+ return fun.apply(parameters);
+ }
});
}
- public void addMathematicalUnaryFunction(String name, Function fun)
+ public void addMathematicalUnaryFunction(final String name, final DoubleUnaryOperator fun)
{
- addUnaryFunction(name, (v) -> new NumericValue(fun.apply(NumericValue.asNumber(v).getDouble())));
+ addUnaryFunction(name, (v) -> new NumericValue(fun.applyAsDouble(NumericValue.asNumber(v).getDouble())));
}
- public void addMathematicalUnaryIntFunction(String name, Function fun)
+ public void addMathematicalUnaryIntFunction(final String name, final DoubleToLongFunction fun)
{
- addUnaryFunction(name, (v) -> new NumericValue(fun.apply(NumericValue.asNumber(v).getDouble())));
+ addUnaryFunction(name, (v) -> new NumericValue(fun.applyAsLong(NumericValue.asNumber(v).getDouble())));
}
- public void addMathematicalBinaryIntFunction(String name, BiFunction fun)
+ public void addMathematicalBinaryIntFunction(final String name, final BinaryOperator fun)
{
addBinaryFunction(name, (w, v) ->
new NumericValue(fun.apply(NumericValue.asNumber(w).getLong(), NumericValue.asNumber(v).getLong())));
}
-
- public void addMathematicalBinaryFunction(String name, BiFunction fun)
+
+ public void addMathematicalBinaryFunction(final String name, final BinaryOperator fun)
{
addBinaryFunction(name, (w, v) ->
new NumericValue(fun.apply(NumericValue.asNumber(w).getDouble(), NumericValue.asNumber(v).getDouble())));
}
- public void addLazyFunction(String name, int numParams, TriFunction, LazyValue> fun)
+ public void addLazyFunction(final String name, final int numParams, final TriFunction, LazyValue> fun)
{
functions.put(name, new AbstractLazyFunction(numParams, name)
{
@Override
- public boolean pure() {
+ public boolean pure()
+ {
return false;
}
@Override
- public boolean transitive() {
+ public boolean transitive()
+ {
return false;
}
@Override
- public LazyValue lazyEval(Context c, Context.Type i, Expression e, Tokenizer.Token t, List lazyParams)
+ public LazyValue lazyEval(final Context c, final Context.Type i, final Expression e, final Tokenizer.Token t, final List lazyParams)
{
ILazyFunction.checkInterrupts();
if (numParams >= 0 && lazyParams.size() != numParams)
{
- String error = "Function '"+name+"' requires "+numParams+" arguments, got "+lazyParams.size()+". ";
+ final String error = "Function '" + name + "' requires " + numParams + " arguments, got " + lazyParams.size() + ". ";
throw new InternalExpressionException(error + (fun instanceof Fluff.UsageProvider up ? up.getUsage() : ""));
}
@@ -510,7 +578,7 @@ public class Expression
{
return fun.apply(c, i, lazyParams);
}
- catch (RuntimeException exc)
+ catch (final RuntimeException exc)
{
throw handleCodeException(c, exc, e, t);
}
@@ -518,29 +586,31 @@ public class Expression
});
}
- public void addLazyFunction(String name, TriFunction, LazyValue> fun)
+ public void addLazyFunction(final String name, final TriFunction, LazyValue> fun)
{
functions.put(name, new AbstractLazyFunction(-1, name)
{
@Override
- public boolean pure() {
+ public boolean pure()
+ {
return false;
}
@Override
- public boolean transitive() {
+ public boolean transitive()
+ {
return false;
}
@Override
- public LazyValue lazyEval(Context c, Context.Type i, Expression e, Tokenizer.Token t, List lazyParams)
+ public LazyValue lazyEval(final Context c, final Context.Type i, final Expression e, final Tokenizer.Token t, final List lazyParams)
{
ILazyFunction.checkInterrupts();
try
{
return fun.apply(c, i, lazyParams);
}
- catch (RuntimeException exc)
+ catch (final RuntimeException exc)
{
throw handleCodeException(c, exc, e, t);
}
@@ -548,35 +618,37 @@ public class Expression
});
}
- public void addPureLazyFunction(String name, int num_params, Function typer, TriFunction, LazyValue> fun)
+ public void addPureLazyFunction(final String name, final int num_params, final Function typer, final TriFunction, LazyValue> fun)
{
functions.put(name, new AbstractLazyFunction(num_params, name)
{
@Override
- public boolean pure() {
+ public boolean pure()
+ {
return true;
}
@Override
- public boolean transitive() {
+ public boolean transitive()
+ {
return false;
}
@Override
- public Context.Type staticType(Context.Type outerType)
+ public Context.Type staticType(final Context.Type outerType)
{
return typer.apply(outerType);
}
@Override
- public LazyValue lazyEval(Context c, Context.Type i, Expression e, Tokenizer.Token t, List lazyParams)
+ public LazyValue lazyEval(final Context c, final Context.Type i, final Expression e, final Tokenizer.Token t, final List lazyParams)
{
ILazyFunction.checkInterrupts();
try
{
return fun.apply(c, i, lazyParams);
}
- catch (RuntimeException exc)
+ catch (final RuntimeException exc)
{
throw handleCodeException(c, exc, e, t);
}
@@ -584,30 +656,32 @@ public class Expression
});
}
- public void addContextFunction(String name, int num_params, TriFunction, Value> fun)
+ public void addContextFunction(final String name, final int num_params, final TriFunction, Value> fun)
{
functions.put(name, new AbstractLazyFunction(num_params, name)
{
@Override
- public boolean pure() {
+ public boolean pure()
+ {
return false;
}
@Override
- public boolean transitive() {
+ public boolean transitive()
+ {
return false;
}
@Override
- public LazyValue lazyEval(Context c, Context.Type i, Expression e, Tokenizer.Token t, List lazyParams)
+ public LazyValue lazyEval(final Context c, final Context.Type i, final Expression e, final Tokenizer.Token t, final List lazyParams)
{
ILazyFunction.checkInterrupts();
try
{
- Value ret = fun.apply(c, i, unpackArgs(lazyParams, c, Context.NONE));
+ final Value ret = fun.apply(c, i, unpackArgs(lazyParams, c, Context.NONE));
return (cc, tt) -> ret;
}
- catch (RuntimeException exc)
+ catch (final RuntimeException exc)
{
throw handleCodeException(c, exc, e, t);
}
@@ -615,34 +689,37 @@ public class Expression
});
}
- public void addTypedContextFunction(String name, int num_params, Context.Type reqType, TriFunction, Value> fun)
+ public void addTypedContextFunction(final String name, final int num_params, final Context.Type reqType, final TriFunction, Value> fun)
{
functions.put(name, new AbstractLazyFunction(num_params, name)
{
@Override
- public boolean pure() {
+ public boolean pure()
+ {
return true;
}
@Override
- public boolean transitive() {
+ public boolean transitive()
+ {
return false;
}
@Override
- public Context.Type staticType(Context.Type outerType) {
+ public Context.Type staticType(final Context.Type outerType)
+ {
return reqType;
}
@Override
- public LazyValue lazyEval(Context c, Context.Type i, Expression e, Tokenizer.Token t, List lazyParams)
+ public LazyValue lazyEval(final Context c, final Context.Type i, final Expression e, final Tokenizer.Token t, final List lazyParams)
{
try
{
- Value ret = fun.apply(c, i, unpackArgs(lazyParams, c, reqType));
+ final Value ret = fun.apply(c, i, unpackArgs(lazyParams, c, reqType));
return (cc, tt) -> ret;
}
- catch (RuntimeException exc)
+ catch (final RuntimeException exc)
{
throw handleCodeException(c, exc, e, t);
}
@@ -650,34 +727,42 @@ public class Expression
});
}
- public FunctionValue createUserDefinedFunction(Context context, String name, Expression expr, Tokenizer.Token token, List arguments, String varArgs, List outers, LazyValue code)
+ public FunctionValue createUserDefinedFunction(final Context context, final String name, final Expression expr, final Tokenizer.Token token, final List arguments, final String varArgs, final List outers, final LazyValue code)
{
if (functions.containsKey(name))
- throw new ExpressionException(context, expr, token, "Function "+name+" would mask a built-in function");
- Map contextValues = new HashMap<>();
- for (String outer : outers)
{
- LazyValue lv = context.getVariable(outer);
+ throw new ExpressionException(context, expr, token, "Function " + name + " would mask a built-in function");
+ }
+ Map contextValues = new HashMap<>();
+ for (final String outer : outers)
+ {
+ final LazyValue lv = context.getVariable(outer);
if (lv == null)
{
- throw new InternalExpressionException("Variable "+outer+" needs to be defined in outer scope to be used as outer parameter, and cannot be global");
+ throw new InternalExpressionException("Variable " + outer + " needs to be defined in outer scope to be used as outer parameter, and cannot be global");
}
else
{
contextValues.put(outer, lv);
}
}
- if (contextValues.isEmpty()) contextValues = null;
+ if (contextValues.isEmpty())
+ {
+ contextValues = null;
+ }
- FunctionValue result = new FunctionValue(expr, token, name, code, arguments, varArgs, contextValues);
+ final FunctionValue result = new FunctionValue(expr, token, name, code, arguments, varArgs, contextValues);
// do not store lambda definitions
- if (!name.equals("_")) context.host.addUserDefinedFunction(context, module, name, result);
+ if (!name.equals("_"))
+ {
+ context.host.addUserDefinedFunction(context, module, name, result);
+ }
return result;
}
- public void alias(String copy, String original)
+ public void alias(final String copy, final String original)
{
- ILazyFunction originalFunction = functions.get(original);
+ final ILazyFunction originalFunction = functions.get(original);
functions.put(copy, new ILazyFunction()
{
@Override
@@ -693,31 +778,34 @@ public class Expression
}
@Override
- public boolean pure() {
+ public boolean pure()
+ {
return originalFunction.pure();
}
@Override
- public boolean transitive() {
+ public boolean transitive()
+ {
return originalFunction.transitive();
}
@Override
- public Context.Type staticType(Context.Type outerType) {
+ public Context.Type staticType(final Context.Type outerType)
+ {
return originalFunction.staticType(outerType);
}
@Override
- public LazyValue lazyEval(Context c, Context.Type type, Expression expr, Tokenizer.Token token, List lazyParams)
+ public LazyValue lazyEval(final Context c, final Context.Type type, final Expression expr, final Tokenizer.Token token, final List lazyParams)
{
- c.host.issueDeprecation(copy+"(...)");
+ c.host.issueDeprecation(copy + "(...)");
return originalFunction.lazyEval(c, type, expr, token, lazyParams);
}
});
}
- public void setAnyVariable(Context c, String name, LazyValue lv)
+ public void setAnyVariable(final Context c, final String name, final LazyValue lv)
{
if (name.startsWith("global_"))
{
@@ -729,28 +817,35 @@ public class Expression
}
}
- public LazyValue getOrSetAnyVariable(Context c, String name)
+ public LazyValue getOrSetAnyVariable(final Context c, final String name)
{
- LazyValue var;
+ LazyValue variable;
if (!name.startsWith("global_"))
{
- var = c.getVariable(name);
- if (var != null) return var;
+ variable = c.getVariable(name);
+ if (variable != null)
+ {
+ return variable;
+ }
}
- var = c.host.getGlobalVariable(module, name);
- if (var != null) return var;
- var = (_c, _t ) -> _c.host.strict ? Value.UNDEF.reboundedTo(name) : Value.NULL.reboundedTo(name);
- setAnyVariable(c, name, var);
- return var;
+ variable = c.host.getGlobalVariable(module, name);
+ if (variable != null)
+ {
+ return variable;
+ }
+ variable = (_c, _t) -> _c.host.strict ? Value.UNDEF.reboundedTo(name) : Value.NULL.reboundedTo(name);
+ setAnyVariable(c, name, variable);
+ return variable;
}
public static final Expression none = new Expression("null");
+
/**
* @param expression .
*/
- public Expression(String expression)
+ public Expression(final String expression)
{
- this.expression = expression.stripTrailing().replaceAll("\\r\\n?", "\n").replaceAll("\\t"," ");
+ this.expression = expression.stripTrailing().replaceAll("\\r\\n?", "\n").replaceAll("\\t", " ");
Operators.apply(this);
ControlFlow.apply(this);
Functions.apply(this);
@@ -762,26 +857,25 @@ public class Expression
}
- private List shuntingYard(Context c)
+ private List shuntingYard(final Context c)
{
- List outputQueue = new ArrayList<>();
- Stack stack = new ObjectArrayList<>();
+ final List outputQueue = new ArrayList<>();
+ final Stack stack = new ObjectArrayList<>();
- Tokenizer tokenizer = new Tokenizer(c, this, expression, allowComments, allowNewlineSubstitutions);
+ final Tokenizer tokenizer = new Tokenizer(c, this, expression, allowComments, allowNewlineSubstitutions);
// stripping lousy but acceptable semicolons
- List cleanedTokens = tokenizer.postProcess();
+ final List cleanedTokens = tokenizer.postProcess();
Tokenizer.Token lastFunction = null;
Tokenizer.Token previousToken = null;
- for (Tokenizer.Token token : cleanedTokens)
+ for (final Tokenizer.Token token : cleanedTokens)
{
switch (token.type)
{
case STRINGPARAM:
//stack.push(token); // changed that so strings are treated like literals
//break;
- case LITERAL:
- case HEX_LITERAL:
+ case LITERAL, HEX_LITERAL:
if (previousToken != null && (
previousToken.type == Tokenizer.Token.TokenType.LITERAL ||
previousToken.type == Tokenizer.Token.TokenType.HEX_LITERAL ||
@@ -824,9 +918,9 @@ public class Expression
if (previousToken != null
&& (previousToken.type == Tokenizer.Token.TokenType.COMMA || previousToken.type == Tokenizer.Token.TokenType.OPEN_PAREN))
{
- throw new ExpressionException(c, this, token, "Missing parameter(s) for operator '" + token+"'");
+ throw new ExpressionException(c, this, token, "Missing parameter(s) for operator '" + token + "'");
}
- ILazyOperator o1 = operators.get(token.surface);
+ final ILazyOperator o1 = operators.get(token.surface);
if (o1 == null)
{
throw new ExpressionException(c, this, token, "Unknown operator '" + token + "'");
@@ -841,9 +935,9 @@ public class Expression
if (previousToken != null && previousToken.type != Tokenizer.Token.TokenType.OPERATOR
&& previousToken.type != Tokenizer.Token.TokenType.COMMA && previousToken.type != Tokenizer.Token.TokenType.OPEN_PAREN)
{
- throw new ExpressionException(c, this, token, "Invalid position for unary operator " + token );
+ throw new ExpressionException(c, this, token, "Invalid position for unary operator " + token);
}
- ILazyOperator o1 = operators.get(token.surface);
+ final ILazyOperator o1 = operators.get(token.surface);
if (o1 == null)
{
throw new ExpressionException(c, this, token, "Unknown unary operator '" + token.surface.substring(0, token.surface.length() - 1) + "'");
@@ -854,24 +948,10 @@ public class Expression
break;
}
case OPEN_PAREN:
- if (previousToken != null)
+ // removed implicit multiplication in this missing code block
+ if (previousToken != null && previousToken.type == Tokenizer.Token.TokenType.FUNCTION)
{
- //if (previousToken.type == Tokenizer.Token.TokenType.LITERAL || previousToken.type == Tokenizer.Token.TokenType.CLOSE_PAREN
- // || previousToken.type == Tokenizer.Token.TokenType.VARIABLE
- // || previousToken.type == Tokenizer.Token.TokenType.HEX_LITERAL)
- //{
- // Implicit multiplication, e.g. 23(a+b) or (a+b)(a-b)
- // Tokenizer.Token multiplication = new Tokenizer.Token();
- // multiplication.append("*");
- // multiplication.type = Tokenizer.Token.TokenType.OPERATOR;
- // stack.push(multiplication);
- //}
- // if the ( is preceded by a valid function, then it
- // denotes the start of a parameter list
- if (previousToken.type == Tokenizer.Token.TokenType.FUNCTION)
- {
- outputQueue.add(token);
- }
+ outputQueue.add(token);
}
stack.push(token);
break;
@@ -897,18 +977,21 @@ public class Expression
case MARKER:
if ("$".equals(token.surface))
{
- StringBuilder sb = new StringBuilder(expression);
+ final StringBuilder sb = new StringBuilder(expression);
sb.setCharAt(token.pos, '\n');
expression = sb.toString();
}
break;
}
- if (token.type != Tokenizer.Token.TokenType.MARKER) previousToken = token;
+ if (token.type != Tokenizer.Token.TokenType.MARKER)
+ {
+ previousToken = token;
+ }
}
while (!stack.isEmpty())
{
- Tokenizer.Token element = stack.pop();
+ final Tokenizer.Token element = stack.pop();
if (element.type == Tokenizer.Token.TokenType.OPEN_PAREN || element.type == Tokenizer.Token.TokenType.CLOSE_PAREN)
{
throw new ExpressionException(c, this, element, "Mismatched parentheses");
@@ -918,7 +1001,7 @@ public class Expression
return outputQueue;
}
- private void shuntOperators(List outputQueue, Stack stack, ILazyOperator o1)
+ private void shuntOperators(final List outputQueue, final Stack stack, final ILazyOperator o1)
{
Tokenizer.Token nextToken = stack.isEmpty() ? null : stack.top();
while (nextToken != null
@@ -932,7 +1015,7 @@ public class Expression
}
}
- public Value eval(Context c)
+ public Value eval(final Context c)
{
if (ast == null)
{
@@ -941,31 +1024,31 @@ public class Expression
return evalValue(() -> ast, c, Context.Type.NONE);
}
- public Value evalValue(Supplier exprProvider, Context c, Context.Type expectedType)
+ public Value evalValue(final Supplier exprProvider, final Context c, final Context.Type expectedType)
{
try
{
return exprProvider.get().evalValue(c, expectedType);
}
- catch (ContinueStatement | BreakStatement | ReturnStatement exc)
+ catch (final ContinueStatement | BreakStatement | ReturnStatement exc)
{
throw new ExpressionException(c, this, "Control flow functions, like continue, break or return, should only be used in loops, and functions respectively.");
}
- catch (ExitStatement exit)
+ catch (final ExitStatement exit)
{
- return exit.retval==null?Value.NULL:exit.retval;
+ return exit.retval == null ? Value.NULL : exit.retval;
}
- catch (StackOverflowError ignored)
+ catch (final StackOverflowError ignored)
{
throw new ExpressionException(c, this, "Your thoughts are too deep");
}
- catch (InternalExpressionException exc)
+ catch (final InternalExpressionException exc)
{
- throw new ExpressionException(c, this, "Your expression result is incorrect: "+exc.getMessage());
+ throw new ExpressionException(c, this, "Your expression result is incorrect: " + exc.getMessage());
}
- catch (ArithmeticException exc)
+ catch (final ArithmeticException exc)
{
- throw new ExpressionException(c, this, "The final result is incorrect: "+exc.getMessage());
+ throw new ExpressionException(c, this, "The final result is incorrect: " + exc.getMessage());
}
}
@@ -980,7 +1063,8 @@ public class Expression
* varying numbers of function parameters.
*/
public static final ExpressionNode PARAMS_START = new ExpressionNode(null, null, Tokenizer.Token.NONE);
- public ExpressionNode(LazyValue op, List args, Tokenizer.Token token)
+
+ public ExpressionNode(final LazyValue op, final List args, final Tokenizer.Token token)
{
this.op = op;
this.args = args;
@@ -988,49 +1072,48 @@ public class Expression
range = new ArrayList<>();
range.add(token);
}
- public static ExpressionNode ofConstant(Value val, Tokenizer.Token token)
+
+ public static ExpressionNode ofConstant(final Value val, final Tokenizer.Token token)
{
return new ExpressionNode(new LazyValue.Constant(val), Collections.emptyList(), token);
}
}
- private ExpressionNode RPNToParseTree(List tokens, Context context)
+ private ExpressionNode RPNToParseTree(final List tokens, final Context context)
{
- Stack nodeStack = new ObjectArrayList<>();
+ final Stack nodeStack = new ObjectArrayList<>();
for (final Tokenizer.Token token : tokens)
{
- switch (token.type)
- {
- case UNARY_OPERATOR:
- {
+ switch (token.type) {
+ case UNARY_OPERATOR -> {
final ExpressionNode node = nodeStack.pop();
- LazyValue result = (c, t) -> operators.get(token.surface).lazyEval(c, t, this, token, node.op, null).evalValue(c, t);
+ final LazyValue result = (c, t) -> operators.get(token.surface).lazyEval(c, t, this, token, node.op, null).evalValue(c, t);
nodeStack.push(new ExpressionNode(result, Collections.singletonList(node), token));
- break;
}
- case OPERATOR:
+ case OPERATOR -> {
final ExpressionNode v1 = nodeStack.pop();
final ExpressionNode v2 = nodeStack.pop();
- LazyValue result = (c,t) -> operators.get(token.surface).lazyEval(c, t,this, token, v2.op, v1.op).evalValue(c, t);
- nodeStack.push(new ExpressionNode(result, List.of(v2, v1), token ));
- break;
- case VARIABLE:
- Value constant = getConstantFor(token.surface);
+ final LazyValue result = (c, t) -> operators.get(token.surface).lazyEval(c, t, this, token, v2.op, v1.op).evalValue(c, t);
+ nodeStack.push(new ExpressionNode(result, List.of(v2, v1), token));
+ }
+ case VARIABLE -> {
+ final Value constant = getConstantFor(token.surface);
if (constant != null)
{
token.morph(Tokenizer.Token.TokenType.CONSTANT, token.surface);
nodeStack.push(new ExpressionNode(LazyValue.ofConstant(constant), Collections.emptyList(), token));
}
- else {
+ else
+ {
nodeStack.push(new ExpressionNode(((c, t) -> getOrSetAnyVariable(c, token.surface).evalValue(c, t)), Collections.emptyList(), token));
}
- break;
- case FUNCTION:
- String name = token.surface;
- ILazyFunction f;
- ArrayList p;
- boolean isKnown = functions.containsKey(name); // globals will be evaluated lazily, not at compile time via .
+ }
+ case FUNCTION -> {
+ final String name = token.surface;
+ final ILazyFunction f;
+ final ArrayList p;
+ final boolean isKnown = functions.containsKey(name); // globals will be evaluated lazily, not at compile time via .
if (isKnown)
{
f = functions.get(name);
@@ -1053,190 +1136,230 @@ public class Expression
token.morph(Tokenizer.Token.TokenType.FUNCTION, "call");
}
Collections.reverse(p);
-
if (nodeStack.top() == ExpressionNode.PARAMS_START)
{
nodeStack.pop();
- };
- List params = p.stream().map(n -> n.op).collect(Collectors.toList());
-
+ }
+ final List params = p.stream().map(n -> n.op).collect(Collectors.toList());
nodeStack.push(new ExpressionNode(
(c, t) -> f.lazyEval(c, t, this, token, params).evalValue(c, t),
- p,token
+ p, token
));
- break;
- case OPEN_PAREN:
- nodeStack.push(ExpressionNode.PARAMS_START);
- break;
- case LITERAL:
- Value number;
+ }
+ case OPEN_PAREN -> nodeStack.push(ExpressionNode.PARAMS_START);
+ case LITERAL -> {
+ final Value number;
try
{
number = new NumericValue(token.surface);
}
- catch (NumberFormatException exception)
+ catch (final NumberFormatException exception)
{
throw new ExpressionException(context, this, token, "Not a number");
}
token.morph(Tokenizer.Token.TokenType.CONSTANT, token.surface);
nodeStack.push(ExpressionNode.ofConstant(number, token));
- break;
- case STRINGPARAM:
+ }
+ case STRINGPARAM -> {
token.morph(Tokenizer.Token.TokenType.CONSTANT, token.surface);
nodeStack.push(ExpressionNode.ofConstant(new StringValue(token.surface), token));
- break;
- case HEX_LITERAL:
- Value hexNumber;
+ }
+ case HEX_LITERAL -> {
+ final Value hexNumber;
try
{
hexNumber = new NumericValue(new BigInteger(token.surface.substring(2), 16).longValue());
}
- catch (NumberFormatException exception)
+ catch (final NumberFormatException exception)
{
throw new ExpressionException(context, this, token, "Not a number");
}
token.morph(Tokenizer.Token.TokenType.CONSTANT, token.surface);
nodeStack.push(ExpressionNode.ofConstant(hexNumber, token));
- break;
- default:
- throw new ExpressionException(context, this, token, "Unexpected token '" + token.surface + "'");
+ }
+ default -> throw new ExpressionException(context, this, token, "Unexpected token '" + token.surface + "'");
}
}
return nodeStack.pop();
}
- private LazyValue getAST(Context context)
+ private LazyValue getAST(final Context context)
{
- //Stack stack = new Stack<>();
- List rpn = shuntingYard(context);
+ final List rpn = shuntingYard(context);
validate(context, rpn);
- ExpressionNode root = RPNToParseTree(rpn, context);
+ final ExpressionNode root = RPNToParseTree(rpn, context);
if (!CarpetSettings.scriptsOptimization)
+ {
return root.op;
+ }
- Context optimizeOnlyContext = new Context.ContextForErrorReporting(context);
+ final Context optimizeOnlyContext = new Context.ContextForErrorReporting(context);
if (CarpetSettings.scriptsDebugging)
- CarpetScriptServer.LOG.info("Input code size for "+getModuleName()+": " + treeSize(root) + " nodes, " + treeDepth(root) + " deep");
+ {
+ CarpetScriptServer.LOG.info("Input code size for " + getModuleName() + ": " + treeSize(root) + " nodes, " + treeDepth(root) + " deep");
+ }
// Defined out here to not need to conditionally assign them with debugging disabled
int prevTreeSize = -1;
int prevTreeDepth = -1;
boolean changed = true;
- while(changed) {
+ while (changed)
+ {
changed = false;
- while (true) {
- if (CarpetSettings.scriptsDebugging) {
+ while (true)
+ {
+ if (CarpetSettings.scriptsDebugging)
+ {
prevTreeSize = treeSize(root);
prevTreeDepth = treeDepth(root);
}
- boolean optimized = compactTree(root, Context.Type.NONE, 0);
- if (!optimized) break;
+ final boolean optimized = compactTree(root, Context.Type.NONE, 0);
+ if (!optimized)
+ {
+ break;
+ }
changed = true;
if (CarpetSettings.scriptsDebugging)
+ {
CarpetScriptServer.LOG.info("Compacted from " + prevTreeSize + " nodes, " + prevTreeDepth + " code depth to " + treeSize(root) + " nodes, " + treeDepth(root) + " code depth");
+ }
}
- while (true) {
- if (CarpetSettings.scriptsDebugging) {
+ while (true)
+ {
+ if (CarpetSettings.scriptsDebugging)
+ {
prevTreeSize = treeSize(root);
prevTreeDepth = treeDepth(root);
}
- boolean optimized = optimizeTree(optimizeOnlyContext, root, Context.Type.NONE, 0);
- if (!optimized) break;
+ final boolean optimized = optimizeTree(optimizeOnlyContext, root, Context.Type.NONE, 0);
+ if (!optimized)
+ {
+ break;
+ }
changed = true;
if (CarpetSettings.scriptsDebugging)
+ {
CarpetScriptServer.LOG.info("Optimized from " + prevTreeSize + " nodes, " + prevTreeDepth + " code depth to " + treeSize(root) + " nodes, " + treeDepth(root) + " code depth");
+ }
}
}
return extractOp(optimizeOnlyContext, root, Context.Type.NONE);
}
- private int treeSize(ExpressionNode node)
+ private int treeSize(final ExpressionNode node)
{
- if (node.op instanceof LazyValue.ContextFreeLazyValue) return 1;
- return node.args.stream().mapToInt(this::treeSize).sum()+1;
+ return node.op instanceof LazyValue.ContextFreeLazyValue ? 1 : node.args.stream().mapToInt(this::treeSize).sum() + 1;
}
- private int treeDepth(ExpressionNode node)
+
+ private int treeDepth(final ExpressionNode node)
{
- if (node.op instanceof LazyValue.ContextFreeLazyValue) return 1;
- return node.args.stream().mapToInt(this::treeDepth).max().orElse(0)+1;
+ return node.op instanceof LazyValue.ContextFreeLazyValue ? 1 : node.args.stream().mapToInt(this::treeDepth).max().orElse(0) + 1;
}
- private boolean compactTree(ExpressionNode node, Context.Type expectedType, int indent) {
+ private boolean compactTree(final ExpressionNode node, final Context.Type expectedType, final int indent)
+ {
// ctx is just to report errors, not values evaluation
boolean optimized = false;
- Tokenizer.Token.TokenType token = node.token.type;
- if (!token.isFunctional()) return false;
+ final Tokenizer.Token.TokenType token = node.token.type;
+ if (!token.isFunctional())
+ {
+ return false;
+ }
// input special cases here, like function signature
- if (node.op instanceof LazyValue.Constant) return false; // optimized already
+ if (node.op instanceof LazyValue.Constant)
+ {
+ return false; // optimized already
+ }
// function or operator
- String symbol = node.token.surface;
- Fluff.EvalNode operation = ((token == Tokenizer.Token.TokenType.FUNCTION) ? functions : operators).get(symbol);
- Context.Type requestedType = operation.staticType(expectedType);
- for (ExpressionNode arg : node.args) {
- if (compactTree(arg, requestedType, indent+1)) optimized = true;
+ final String symbol = node.token.surface;
+ final Fluff.EvalNode operation = ((token == Tokenizer.Token.TokenType.FUNCTION) ? functions : operators).get(symbol);
+ final Context.Type requestedType = operation.staticType(expectedType);
+ for (final ExpressionNode arg : node.args)
+ {
+ if (compactTree(arg, requestedType, indent + 1))
+ {
+ optimized = true;
+ }
}
- if (expectedType != Context.Type.MAPDEF && symbol.equals("->") && node.args.size() == 2) {
- String rop = node.args.get(1).token.surface;
+ if (expectedType != Context.Type.MAPDEF && symbol.equals("->") && node.args.size() == 2)
+ {
+ final String rop = node.args.get(1).token.surface;
ExpressionNode returnNode = null;
- if ((rop.equals(";") || rop.equals("then"))) {
- List thenArgs = node.args.get(1).args;
- if (thenArgs.size() > 1 && thenArgs.get(thenArgs.size() - 1).token.surface.equals("return")) {
+ if ((rop.equals(";") || rop.equals("then")))
+ {
+ final List thenArgs = node.args.get(1).args;
+ if (thenArgs.size() > 1 && thenArgs.get(thenArgs.size() - 1).token.surface.equals("return"))
+ {
returnNode = thenArgs.get(thenArgs.size() - 1);
}
- } else if (rop.equals("return")) {
+ }
+ else if (rop.equals("return"))
+ {
returnNode = node.args.get(1);
}
if (returnNode != null) // tail return
{
- if (returnNode.args.size() > 0) {
+ if (!returnNode.args.isEmpty())
+ {
returnNode.op = returnNode.args.get(0).op;
returnNode.token = returnNode.args.get(0).token;
returnNode.range = returnNode.args.get(0).range;
returnNode.args = returnNode.args.get(0).args;
if (CarpetSettings.scriptsDebugging)
+ {
CarpetScriptServer.LOG.info(" - Removed unnecessary tail return of " + returnNode.token.surface + " from function body at line " + (returnNode.token.lineno + 1) + ", node depth " + indent);
-
- } else {
+ }
+ }
+ else
+ {
returnNode.op = LazyValue.ofConstant(Value.NULL);
returnNode.token.morph(Tokenizer.Token.TokenType.CONSTANT, "");
returnNode.args = Collections.emptyList();
if (CarpetSettings.scriptsDebugging)
+ {
CarpetScriptServer.LOG.info(" - Removed unnecessary tail return from function body at line " + (returnNode.token.lineno + 1) + ", node depth " + indent);
-
+ }
}
}
}
- for (Map.Entry pair : functionalEquivalence.entrySet()) {
- String operator = pair.getKey();
- String function = pair.getValue();
+ for (final Map.Entry pair : functionalEquivalence.entrySet())
+ {
+ final String operator = pair.getKey();
+ final String function = pair.getValue();
if ((symbol.equals(operator) || symbol.equals(function)) && node.args.size() > 0)
{
- boolean leftOptimizable = operators.get(operator).isLeftAssoc();
- ExpressionNode optimizedChild = node.args.get(leftOptimizable?0:(node.args.size()-1));
- String type = optimizedChild.token.surface;
+ final boolean leftOptimizable = operators.get(operator).isLeftAssoc();
+ final ExpressionNode optimizedChild = node.args.get(leftOptimizable ? 0 : (node.args.size() - 1));
+ final String type = optimizedChild.token.surface;
if ((type.equals(operator) || type.equals(function)) && (!(optimizedChild.op instanceof LazyValue.ContextFreeLazyValue)))
{
optimized = true;
- List newargs = new ArrayList<>();
+ final List newargs = new ArrayList<>();
if (leftOptimizable)
{
newargs.addAll(optimizedChild.args);
for (int i = 1; i < node.args.size(); i++)
+ {
newargs.add(node.args.get(i));
+ }
}
else
{
- for (int i = 0; i < node.args.size()-1; i++)
+ for (int i = 0; i < node.args.size() - 1; i++)
+ {
newargs.add(node.args.get(i));
+ }
newargs.addAll(optimizedChild.args);
}
if (CarpetSettings.scriptsDebugging)
+ {
CarpetScriptServer.LOG.info(" - " + symbol + "(" + node.args.size() + ") => " + function + "(" + newargs.size() + ") at line " + (node.token.lineno + 1) + ", node depth " + indent);
+ }
node.token.morph(Tokenizer.Token.TokenType.FUNCTION, function);
node.args = newargs;
}
@@ -1245,131 +1368,155 @@ public class Expression
return optimized;
}
- private boolean optimizeTree(Context ctx, ExpressionNode node, Context.Type expectedType, int indent) {
+ private boolean optimizeTree(final Context ctx, final ExpressionNode node, Context.Type expectedType, final int indent)
+ {
// ctx is just to report errors, not values evaluation
boolean optimized = false;
- Tokenizer.Token.TokenType token = node.token.type;
- if (!token.isFunctional()) return false;
- String symbol = node.token.surface;
+ final Tokenizer.Token.TokenType token = node.token.type;
+ if (!token.isFunctional())
+ {
+ return false;
+ }
+ final String symbol = node.token.surface;
// input special cases here, like function signature
- if (node.op instanceof LazyValue.Constant) return false; // optimized already
+ if (node.op instanceof LazyValue.Constant)
+ {
+ return false; // optimized already
+ }
// function or operator
- Fluff.EvalNode operation = ((token == Tokenizer.Token.TokenType.FUNCTION) ? functions : operators).get(symbol);
- Context.Type requestedType = operation.staticType(expectedType);
- for (ExpressionNode arg : node.args) {
- if (optimizeTree(ctx, arg, requestedType, indent+1)) optimized = true;
+ final Fluff.EvalNode operation = ((token == Tokenizer.Token.TokenType.FUNCTION) ? functions : operators).get(symbol);
+ final Context.Type requestedType = operation.staticType(expectedType);
+ for (final ExpressionNode arg : node.args)
+ {
+ if (optimizeTree(ctx, arg, requestedType, indent + 1))
+ {
+ optimized = true;
+ }
}
- for (ExpressionNode arg : node.args) {
- if (arg.token.type.isConstant()) continue;
- if (arg.op instanceof LazyValue.ContextFreeLazyValue) continue;
+ for (final ExpressionNode arg : node.args)
+ {
+ if (arg.token.type.isConstant())
+ {
+ continue;
+ }
+ if (arg.op instanceof LazyValue.ContextFreeLazyValue)
+ {
+ continue;
+ }
return optimized;
}
// a few exceptions which we don't implement in the framework for simplicity for now
if (!operation.pure())
{
- if (symbol.equals("->") && expectedType == Context.Type.MAPDEF)
+ if (!symbol.equals("->") || expectedType != Context.Type.MAPDEF)
{
-
- }
- else {
return optimized;
}
}
- if (operation.pure())
+ // element access with constant elements will always resolve the same way.
+ if (operation.pure() && symbol.equals(":") && expectedType == Context.Type.LVALUE)
{
- // element access with constant elements will always resolve the same way.
- if (symbol.equals(":") && expectedType == Context.Type.LVALUE)
- {
- expectedType = Context.Type.NONE;
- }
+ expectedType = Context.Type.NONE;
}
List args = new ArrayList<>(node.args.size());
- for (ExpressionNode arg : node.args) {
- try {
- if (arg.op instanceof LazyValue.Constant) {
- Value val = ((LazyValue.Constant) arg.op).get();
+ for (final ExpressionNode arg : node.args)
+ {
+ try
+ {
+ if (arg.op instanceof LazyValue.Constant)
+ {
+ final Value val = ((LazyValue.Constant) arg.op).get();
args.add((c, t) -> val);
}
- else args.add((c, t) -> arg.op.evalValue(ctx, requestedType));
- } catch (NullPointerException npe) {
+ else
+ {
+ args.add((c, t) -> arg.op.evalValue(ctx, requestedType));
+ }
+ }
+ catch (final NullPointerException npe)
+ {
throw new ExpressionException(ctx, this, node.token, "Attempted to evaluate context free expression");
}
}
// applying argument unpacking
- args= AbstractLazyFunction.lazify(AbstractLazyFunction.unpackLazy(args, ctx, requestedType));
- Value result;
+ args = AbstractLazyFunction.lazify(AbstractLazyFunction.unpackLazy(args, ctx, requestedType));
+ final Value result;
if (operation instanceof ILazyFunction)
{
result = ((ILazyFunction) operation).lazyEval(ctx, expectedType, this, node.token, args).evalValue(null, expectedType);
}
else if (args.size() == 1)
{
- result = ((ILazyOperator)operation).lazyEval(ctx, expectedType, this, node.token, args.get(0), null).evalValue(null, expectedType);
+ result = ((ILazyOperator) operation).lazyEval(ctx, expectedType, this, node.token, args.get(0), null).evalValue(null, expectedType);
}
else // args == 2
{
- result = ((ILazyOperator)operation).lazyEval(ctx, expectedType, this, node.token, args.get(0), args.get(1)).evalValue(null, expectedType);
+ result = ((ILazyOperator) operation).lazyEval(ctx, expectedType, this, node.token, args.get(0), args.get(1)).evalValue(null, expectedType);
}
node.op = LazyValue.ofConstant(result);
- //node.token.morph(Tokenizer.Token.TokenType.CONSTANT, node.token.surface);
if (CarpetSettings.scriptsDebugging)
- CarpetScriptServer.LOG.info(" - "+symbol+"("+args.stream().map(a -> a.evalValue(null, requestedType).getString()).collect(Collectors.joining(", "))+") => "+result.getString()+" at line "+(node.token.lineno+1) +", node depth "+indent);
+ {
+ CarpetScriptServer.LOG.info(" - " + symbol + "(" + args.stream().map(a -> a.evalValue(null, requestedType).getString()).collect(Collectors.joining(", ")) + ") => " + result.getString() + " at line " + (node.token.lineno + 1) + ", node depth " + indent);
+ }
return true;
}
- private LazyValue extractOp(Context ctx, ExpressionNode node, Context.Type expectedType)
+ private LazyValue extractOp(final Context ctx, final ExpressionNode node, final Context.Type expectedType)
{
if (node.op instanceof LazyValue.Constant)
{
// constants are immutable
if (node.token.type.isConstant())
{
- Value value = ((LazyValue.Constant) node.op).get();
+ final Value value = ((LazyValue.Constant) node.op).get();
return (c, t) -> value;
}
return node.op;
}
if (node.op instanceof LazyValue.ContextFreeLazyValue)
{
- Value ret = ((LazyValue.ContextFreeLazyValue) node.op).evalType(expectedType);
+ final Value ret = ((LazyValue.ContextFreeLazyValue) node.op).evalType(expectedType);
return (c, t) -> ret;
}
- Tokenizer.Token token = node.token;
+ final Tokenizer.Token token = node.token;
switch (token.type)
{
- case UNARY_OPERATOR: {
- ILazyOperator op = operators.get(token.surface);
- Context.Type requestedType = op.staticType(expectedType);
- LazyValue arg = extractOp(ctx, node.args.get(0), requestedType);
+ case UNARY_OPERATOR:
+ {
+ final ILazyOperator op = operators.get(token.surface);
+ final Context.Type requestedType = op.staticType(expectedType);
+ final LazyValue arg = extractOp(ctx, node.args.get(0), requestedType);
return (c, t) -> op.lazyEval(c, t, this, token, arg, null).evalValue(c, t);
}
- case OPERATOR: {
- ILazyOperator op = operators.get(token.surface);
- Context.Type requestedType = op.staticType(expectedType);
- LazyValue arg = extractOp(ctx, node.args.get(0), requestedType);
- LazyValue arh = extractOp(ctx, node.args.get(1), requestedType);
+ case OPERATOR:
+ {
+ final ILazyOperator op = operators.get(token.surface);
+ final Context.Type requestedType = op.staticType(expectedType);
+ final LazyValue arg = extractOp(ctx, node.args.get(0), requestedType);
+ final LazyValue arh = extractOp(ctx, node.args.get(1), requestedType);
return (c, t) -> op.lazyEval(c, t, this, token, arg, arh).evalValue(c, t);
}
case VARIABLE:
return (c, t) -> getOrSetAnyVariable(c, token.surface).evalValue(c, t);
- case FUNCTION: {
- ILazyFunction f = functions.get(token.surface);
- Context.Type requestedType = f.staticType(expectedType);
- List params = node.args.stream().map(n -> extractOp(ctx, n, requestedType)).collect(Collectors.toList());
+ case FUNCTION:
+ {
+ final ILazyFunction f = functions.get(token.surface);
+ final Context.Type requestedType = f.staticType(expectedType);
+ final List params = node.args.stream().map(n -> extractOp(ctx, n, requestedType)).collect(Collectors.toList());
return (c, t) -> f.lazyEval(c, t, this, token, params).evalValue(c, t);
}
case CONSTANT:
return node.op;
default:
- throw new ExpressionException(ctx, this, node.token, "Unexpected token '" + node.token.type +" "+node.token.surface + "'");
+ throw new ExpressionException(ctx, this, node.token, "Unexpected token '" + node.token.type + " " + node.token.surface + "'");
}
}
- private void validate(Context c, List rpn)
+ private void validate(final Context c, final List rpn)
{
/*-
* Thanks to Norman Ramsey:
@@ -1379,7 +1526,7 @@ public class Expression
// each
// layer on the stack being the count of the number of parameters in
// that scope
- IntArrayList stack = new IntArrayList(); // IntArrayList instead of just IntStack because we need to query the size
+ final IntArrayList stack = new IntArrayList(); // IntArrayList instead of just IntStack because we need to query the size
// push the 'global' scope
stack.push(0);
diff --git a/src/main/java/carpet/script/Fluff.java b/src/main/java/carpet/script/Fluff.java
index 9fa199bc..ca91195e 100644
--- a/src/main/java/carpet/script/Fluff.java
+++ b/src/main/java/carpet/script/Fluff.java
@@ -13,24 +13,33 @@ import java.util.List;
public abstract class Fluff
{
@FunctionalInterface
- public interface TriFunction { R apply(A a, B b, C c); }
+ public interface TriFunction
+ {
+ R apply(A a, B b, C c);
+ }
@FunctionalInterface
- public interface TriConsumer { void accept(A a, B b, C c); }
+ public interface QuadFunction
+ {
+ R apply(A a, B b, C c, D d);
+ }
@FunctionalInterface
- public interface QuadConsumer { void accept(A a, B b, C c, D d); }
+ public interface QuinnFunction
+ {
+ R apply(A a, B b, C c, D d, E e);
+ }
@FunctionalInterface
- public interface QuadFunction { R apply(A a, B b, C c, D d);}
+ public interface SexFunction
+ {
+ R apply(A a, B b, C c, D d, E e, F f);
+ }
- @FunctionalInterface
- public interface QuinnFunction { R apply(A a, B b, C c, D d, E e);}
-
- @FunctionalInterface
- public interface SexFunction { R apply(A a, B b, C c, D d, E e, F f);}
-
- public interface UsageProvider { String getUsage();}
+ public interface UsageProvider
+ {
+ String getUsage();
+ }
public interface EvalNode
{
@@ -49,7 +58,11 @@ public abstract class Fluff
/**
* @return required argument eval type in case its evaluated statically without context but with a given context type
*/
- default Context.Type staticType(Context.Type outerType) {return transitive()?outerType:Context.NONE;};
+ default Context.Type staticType(final Context.Type outerType)
+ {
+ return transitive() ? outerType : Context.NONE;
+ }
+
}
public interface ILazyFunction extends EvalNode
@@ -63,9 +76,11 @@ public abstract class Fluff
static void checkInterrupts()
{
if (ScriptHost.mainThread != Thread.currentThread() && Thread.currentThread().isInterrupted())
+ {
throw new InternalExpressionException("Thread interrupted");
+ }
}
- // lazy function has a chance to change execution based on contxt
+ // lazy function has a chance to change execution based on context
}
public interface IFunction extends ILazyFunction
@@ -92,94 +107,109 @@ public abstract class Fluff
protected String name;
int numParams;
- public AbstractLazyFunction(int numParams, String name)
+ public AbstractLazyFunction(final int numParams, final String name)
{
+ super();
this.numParams = numParams;
this.name = name;
}
- public String getName() {
+ public String getName()
+ {
return name;
}
@Override
- public int getNumParams() {
+ public int getNumParams()
+ {
return numParams;
}
@Override
- public boolean numParamsVaries() {
+ public boolean numParamsVaries()
+ {
return numParams < 0;
}
- public static List unpackLazy(List lzargs, Context c, Context.Type contextType)
+ public static List unpackLazy(final List lzargs, final Context c, final Context.Type contextType)
{
- List args = new ArrayList<>();
- for (LazyValue lv : lzargs)
+ final List args = new ArrayList<>();
+ for (final LazyValue lv : lzargs)
{
- Value arg = lv.evalValue(c, contextType);
+ final Value arg = lv.evalValue(c, contextType);
if (arg instanceof FunctionUnpackedArgumentsValue)
+ {
args.addAll(((ListValue) arg).getItems());
+ }
else
+ {
args.add(arg);
+ }
}
return args;
}
- public List unpackArgs(List lzargs, Context c, Context.Type contextType)
+ public List unpackArgs(final List lzargs, final Context c, final Context.Type contextType)
{
- List args = unpackLazy(lzargs, c, contextType);
+ final List args = unpackLazy(lzargs, c, contextType);
if (!numParamsVaries() && getNumParams() != args.size())
+ {
throw new InternalExpressionException("Function " + getName() + " expected " + getNumParams() + " parameters, got " + args.size());
+ }
return args;
}
- public static List lazify(List args)
+ public static List lazify(final List args)
{
- List lzargs = new ArrayList<>(args.size());
- args.forEach( v -> lzargs.add( (c, t) -> v));
+ final List lzargs = new ArrayList<>(args.size());
+ args.forEach(v -> lzargs.add((c, t) -> v));
return lzargs;
}
}
public abstract static class AbstractFunction extends AbstractLazyFunction implements IFunction
{
- AbstractFunction(int numParams, String name) {
+ AbstractFunction(final int numParams, final String name)
+ {
super(numParams, name);
}
@Override
- public boolean pure() {
+ public boolean pure()
+ {
return true;
}
@Override
- public boolean transitive() {
+ public boolean transitive()
+ {
return false;
}
@Override
- public LazyValue lazyEval(Context cc, Context.Type type, Expression e, Tokenizer.Token t, final List lazyParams)
+ public LazyValue lazyEval(final Context cc, final Context.Type type, final Expression e, final Tokenizer.Token t, final List lazyParams)
{
return new LazyValue()
{ // eager evaluation always ignores the required type and evals params by none default
private List params;
+
@Override
- public Value evalValue(Context c, Context.Type type)
+ public Value evalValue(final Context c, final Context.Type type)
{
ILazyFunction.checkInterrupts();
try
{
return AbstractFunction.this.eval(getParams(c));
}
- catch (RuntimeException exc)
+ catch (final RuntimeException exc)
{
throw Expression.handleCodeException(cc, exc, e, t);
}
}
- private List getParams(Context c)
+
+ private List getParams(final Context c)
{
if (params == null)
{
@@ -202,18 +232,22 @@ public abstract class Fluff
boolean leftAssoc;
- AbstractLazyOperator(int precedence, boolean leftAssoc) {
+ AbstractLazyOperator(final int precedence, final boolean leftAssoc)
+ {
+ super();
this.precedence = precedence;
this.leftAssoc = leftAssoc;
}
@Override
- public int getPrecedence() {
+ public int getPrecedence()
+ {
return precedence;
}
@Override
- public boolean isLeftAssoc() {
+ public boolean isLeftAssoc()
+ {
return leftAssoc;
}
@@ -222,28 +256,32 @@ public abstract class Fluff
public abstract static class AbstractOperator extends AbstractLazyOperator implements IOperator
{
- AbstractOperator(int precedence, boolean leftAssoc) {
+ AbstractOperator(final int precedence, final boolean leftAssoc)
+ {
super(precedence, leftAssoc);
}
+
@Override
- public boolean pure() {
+ public boolean pure()
+ {
return true;
}
@Override
- public boolean transitive() {
+ public boolean transitive()
+ {
return false;
}
@Override
- public LazyValue lazyEval(Context cc, Context.Type type, Expression e, Tokenizer.Token t, final LazyValue v1, final LazyValue v2)
+ public LazyValue lazyEval(final Context cc, final Context.Type type, final Expression e, final Tokenizer.Token t, final LazyValue v1, final LazyValue v2)
{
return (c, typeIgnored) -> {
try
{
return AbstractOperator.this.eval(v1.evalValue(c, Context.Type.NONE), v2.evalValue(c, Context.Type.NONE));
}
- catch (RuntimeException exc)
+ catch (final RuntimeException exc)
{
throw Expression.handleCodeException(cc, exc, e, t);
}
@@ -253,21 +291,25 @@ public abstract class Fluff
public abstract static class AbstractUnaryOperator extends AbstractOperator
{
- AbstractUnaryOperator(int precedence, boolean leftAssoc) {
+ AbstractUnaryOperator(final int precedence, final boolean leftAssoc)
+ {
super(precedence, leftAssoc);
}
+
@Override
- public boolean pure() {
+ public boolean pure()
+ {
return true;
}
@Override
- public boolean transitive() {
+ public boolean transitive()
+ {
return false;
}
@Override
- public LazyValue lazyEval(Context cc, Context.Type type, Expression e, Tokenizer.Token t, final LazyValue v1, final LazyValue v2)
+ public LazyValue lazyEval(final Context cc, final Context.Type type, final Expression e, final Tokenizer.Token t, final LazyValue v1, final LazyValue v2)
{
if (v2 != null)
{
@@ -278,7 +320,7 @@ public abstract class Fluff
{
return AbstractUnaryOperator.this.evalUnary(v1.evalValue(c, Context.Type.NONE));
}
- catch (RuntimeException exc)
+ catch (final RuntimeException exc)
{
throw Expression.handleCodeException(cc, exc, e, t);
}
@@ -286,7 +328,7 @@ public abstract class Fluff
}
@Override
- public Value eval(Value v1, Value v2)
+ public Value eval(final Value v1, final Value v2)
{
throw new IllegalStateException("Shouldn't end up here");
}
diff --git a/src/main/java/carpet/script/LazyValue.java b/src/main/java/carpet/script/LazyValue.java
index 6f0fc15b..88713d08 100644
--- a/src/main/java/carpet/script/LazyValue.java
+++ b/src/main/java/carpet/script/LazyValue.java
@@ -2,7 +2,9 @@ package carpet.script;
import carpet.script.value.Value;
-/** LazyNumber interface created for lazily evaluated functions */
+/**
+ * LazyNumber interface created for lazily evaluated functions
+ */
@FunctionalInterface
public interface LazyValue
{
@@ -11,13 +13,15 @@ public interface LazyValue
LazyValue NULL = (c, t) -> Value.NULL;
LazyValue ZERO = (c, t) -> Value.ZERO;
- public static LazyValue ofConstant(Value val) {
+ static LazyValue ofConstant(final Value val)
+ {
return new Constant(val);
}
Value evalValue(Context c, Context.Type type);
- default Value evalValue(Context c){
+ default Value evalValue(final Context c)
+ {
return evalValue(c, Context.Type.NONE);
}
@@ -28,7 +32,8 @@ public interface LazyValue
Value evalType(Context.Type type);
@Override
- default Value evalValue(Context c, Context.Type type) {
+ default Value evalValue(final Context c, final Context.Type type)
+ {
return evalType(type);
}
}
@@ -38,21 +43,26 @@ public interface LazyValue
{
Value result;
- public Constant(Value value)
+ public Constant(final Value value)
{
result = value;
}
- public Value get() {return result;}
+ public Value get()
+ {
+ return result;
+ }
@Override
- public Value evalType(Context.Type type) {
+ public Value evalType(final Context.Type type)
+ {
return result.fromConstant();
}
@Override
- public Value evalValue(Context c, Context.Type type) {
+ public Value evalValue(final Context c, final Context.Type type)
+ {
return result.fromConstant();
}
}
diff --git a/src/main/java/carpet/script/Module.java b/src/main/java/carpet/script/Module.java
index 8bf86754..b687c073 100644
--- a/src/main/java/carpet/script/Module.java
+++ b/src/main/java/carpet/script/Module.java
@@ -14,23 +14,24 @@ import carpet.script.argument.FileArgument;
import net.minecraft.nbt.Tag;
import net.minecraft.world.level.storage.LevelResource;
-public record Module(String name, String code, boolean library) {
+public record Module(String name, String code, boolean library)
+{
public Module
{
Objects.requireNonNull(name);
Objects.requireNonNull(code);
}
- public static Module fromPath(Path path)
+ public static Module fromPath(final Path path)
{
- boolean library = path.getFileName().toString().endsWith(".scl");
+ final boolean library = path.getFileName().toString().endsWith(".scl");
try
{
- String name = path.getFileName().toString().replaceFirst("\\.scl?","").toLowerCase(Locale.ROOT);
- String code = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
+ final String name = path.getFileName().toString().replaceFirst("\\.scl?", "").toLowerCase(Locale.ROOT);
+ final String code = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
return new Module(name, code, library);
}
- catch (IOException e)
+ catch (final IOException e)
{
throw new IllegalArgumentException("Failed to load scarpet module", e);
}
@@ -38,79 +39,96 @@ public record Module(String name, String code, boolean library) {
/**
* Creates a new {@link Module} with an app located in Carpet's JAR.
+ *
* @param scriptName A {@link String} being the name of the script. The extension will be autocompleted
- * @param isLibrary A {@link boolean} indicating whether or not the script is a library
+ * @param isLibrary A {@link boolean} indicating whether or not the script is a library
* @return The created {@link BundledModule}
*/
- public static Module carpetNative(String scriptName, boolean isLibrary)
+ public static Module carpetNative(final String scriptName, final boolean isLibrary)
{
return fromJarPath("assets/carpet/scripts/", scriptName, isLibrary);
}
-
+
/**
* Creates a new {@link Module} with an app located at a specified path inside some mod's JAR.
- * @see #fromJarPathWithCustomName(String, String, boolean)
- *
- * @param path A {@link String} being the path to the directory where the app is located.
+ *
+ * @param path A {@link String} being the path to the directory where the app is located.
* @param scriptName A {@link String} being the name of the script. The extension will be autocompleted
- * @param isLibrary A {@link boolean} indicating whether or not the script is a library
+ * @param isLibrary A {@link boolean} indicating whether or not the script is a library
* @return The created {@link BundledModule}
+ * @see #fromJarPathWithCustomName(String, String, boolean)
*/
- public static Module fromJarPath(String path, String scriptName, boolean isLibrary) {
- return fromJarPathWithCustomName(path + scriptName + (isLibrary ? ".scl":".sc"), scriptName, isLibrary);
+ public static Module fromJarPath(final String path, final String scriptName, final boolean isLibrary)
+ {
+ return fromJarPathWithCustomName(path + scriptName + (isLibrary ? ".scl" : ".sc"), scriptName, isLibrary);
}
-
+
/**
* Creates a new {@link Module} with an app located at the specified fullPath (inside a mod jar)with a custom name.
- * @see #fromJarPath(String, String, boolean)
- *
- * @param fullPath A {@link String} being the full path to the app's code, including file and extension.
+ *
+ * @param fullPath A {@link String} being the full path to the app's code, including file and extension.
* @param customName A {@link String} being the custom name for the script.
- * @param isLibrary A {@link boolean} indicating whether or not the script is a library
+ * @param isLibrary A {@link boolean} indicating whether or not the script is a library
* @return The created {@link Module}
+ * @see #fromJarPath(String, String, boolean)
*/
- public static Module fromJarPathWithCustomName(String fullPath, String customName, boolean isLibrary) {
+ public static Module fromJarPathWithCustomName(final String fullPath, final String customName, final boolean isLibrary)
+ {
try
{
- String name = customName.toLowerCase(Locale.ROOT);
- String code = IOUtils.toString(
+ final String name = customName.toLowerCase(Locale.ROOT);
+ final String code = IOUtils.toString(
Module.class.getClassLoader().getResourceAsStream(fullPath),
StandardCharsets.UTF_8
);
return new Module(name, code, isLibrary);
}
- catch (IOException e)
+ catch (final IOException e)
{
throw new IllegalArgumentException("Failed to load bundled module", e);
}
}
-
- public static Tag getData(Module module)
+
+ public static Tag getData(final Module module)
{
- Path dataFile = resolveResource(module);
- if (dataFile == null) return null;
- if (!Files.exists(dataFile) || !(Files.isRegularFile(dataFile))) return null;
- synchronized (FileArgument.writeIOSync) { return FileArgument.readTag(dataFile); }
+ final Path dataFile = resolveResource(module);
+ if (dataFile == null || !Files.exists(dataFile) || !(Files.isRegularFile(dataFile)))
+ {
+ return null;
+ }
+ synchronized (FileArgument.writeIOSync)
+ {
+ return FileArgument.readTag(dataFile);
+ }
}
- public static void saveData(Module module, Tag globalState)
+ public static void saveData(final Module module, final Tag globalState)
{
- Path dataFile = resolveResource(module);
- if (dataFile == null) return;
- if (!Files.exists(dataFile.getParent())) {
- try {
+ final Path dataFile = resolveResource(module);
+ if (dataFile == null)
+ {
+ return;
+ }
+ if (!Files.exists(dataFile.getParent()))
+ {
+ try
+ {
Files.createDirectories(dataFile.getParent());
- } catch (IOException e) {
+ }
+ catch (final IOException e)
+ {
throw new IllegalStateException(e);
}
}
- synchronized (FileArgument.writeIOSync) { FileArgument.writeTagDisk(globalState, dataFile, false); }
+ synchronized (FileArgument.writeIOSync)
+ {
+ FileArgument.writeTagDisk(globalState, dataFile, false);
+ }
}
- private static Path resolveResource(Module module)
+ private static Path resolveResource(final Module module)
{
- if (module == null) return null; // commandline app
- return CarpetServer.minecraft_server.getWorldPath(LevelResource.ROOT).resolve("scripts/"+module.name()+".data.nbt");
+ return module == null ? null : CarpetServer.minecraft_server.getWorldPath(LevelResource.ROOT).resolve("scripts/" + module.name() + ".data.nbt"); // commandline app
}
}
diff --git a/src/main/java/carpet/script/ScriptHost.java b/src/main/java/carpet/script/ScriptHost.java
index a8eb3e85..6737be00 100644
--- a/src/main/java/carpet/script/ScriptHost.java
+++ b/src/main/java/carpet/script/ScriptHost.java
@@ -38,41 +38,45 @@ public abstract class ScriptHost
private final Set deprecations = new HashSet<>();
- public Random getRandom(long aLong)
+ public Random getRandom(final long aLong)
{
if (randomizers.size() > 65536)
+ {
randomizers.clear();
+ }
return randomizers.computeIfAbsent(aLong, Random::new);
}
- public boolean resetRandom(long aLong) {
+ public boolean resetRandom(final long aLong)
+ {
return randomizers.remove(aLong) != null;
}
public static class ModuleData
{
Module parent;
- public Map globalFunctions = new Object2ObjectOpenHashMap<>();
- public Map globalVariables = new Object2ObjectOpenHashMap<>();
- public Map functionImports = new Object2ObjectOpenHashMap<>(); // imported functions string to module
- public Map globalsImports = new Object2ObjectOpenHashMap<>(); // imported global variables string to module
- public Map futureImports = new Object2ObjectOpenHashMap<>(); // imports not known before used
+ public final Map globalFunctions = new Object2ObjectOpenHashMap<>();
+ public final Map globalVariables = new Object2ObjectOpenHashMap<>();
+ public final Map functionImports = new Object2ObjectOpenHashMap<>(); // imported functions string to module
+ public final Map globalsImports = new Object2ObjectOpenHashMap<>(); // imported global variables string to module
+ public final Map futureImports = new Object2ObjectOpenHashMap<>(); // imports not known before used
- public ModuleData(Module parent, ModuleData other)
+ public ModuleData(final Module parent, final ModuleData other)
{
+ super();
// imports are just pointers, but they still point to the wrong modules (point to the parent)
this.parent = parent;
globalFunctions.putAll(other.globalFunctions);
other.globalVariables.forEach((key, value) ->
{
- Value var = value.evalValue(null);
- Value copy = var.deepcopy();
+ final Value var = value.evalValue(null);
+ final Value copy = var.deepcopy();
copy.boundVariable = var.boundVariable;
globalVariables.put(key, (c, t) -> copy);
});
}
- public void setImportsBasedOn(ScriptHost host, ModuleData other)
+ public void setImportsBasedOn(final ScriptHost host, final ModuleData other)
{
// fixing imports
other.functionImports.forEach((name, targetData) -> {
@@ -87,20 +91,24 @@ public abstract class ScriptHost
}
- public ModuleData(Module parent)
+ public ModuleData(final Module parent)
{
this.parent = parent;
}
}
+
protected final Map userHosts = new Object2ObjectOpenHashMap<>();
- private Map moduleData = new HashMap<>(); // marking imports
- private Map modules = new HashMap<>();
+ private final Map moduleData = new HashMap<>(); // marking imports
+ private final Map modules = new HashMap<>();
protected ScriptHost parent;
protected boolean perUser;
public String user;
- public String getName() {return main ==null?null: main.name();}
+ public String getName()
+ {
+ return main == null ? null : main.name();
+ }
public final Module main;
@@ -109,9 +117,10 @@ public abstract class ScriptHost
{
List apply(Expression expression, Tokenizer.Token token, Context context, String message);
}
+
public ErrorSnooper errorSnooper = null;
- protected ScriptHost(Module code, ScriptServer scriptServer, boolean perUser, ScriptHost parent)
+ protected ScriptHost(final Module code, final ScriptServer scriptServer, final boolean perUser, final ScriptHost parent)
{
this.parent = parent;
this.main = code;
@@ -119,24 +128,30 @@ public abstract class ScriptHost
this.user = null;
this.strict = false;
this.scriptServer = scriptServer;
- ModuleData moduleData = new ModuleData(code);
+ final ModuleData moduleData = new ModuleData(code);
initializeModuleGlobals(moduleData);
this.moduleData.put(code, moduleData);
- this.modules.put(code==null?null:code.name(), code);
+ this.modules.put(code == null ? null : code.name(), code);
mainThread = Thread.currentThread();
}
- void initializeModuleGlobals(ModuleData md)
+ void initializeModuleGlobals(final ModuleData md)
{
}
- public void importModule(Context c, String moduleName)
+ public void importModule(final Context c, final String moduleName)
{
- if (modules.containsKey(moduleName.toLowerCase(Locale.ROOT))) return; // aready imported
- Module module = getModuleOrLibraryByName(moduleName);
- if (modules.containsKey(module.name())) return; // aready imported, once again, in case some discrepancies in names?
+ if (modules.containsKey(moduleName.toLowerCase(Locale.ROOT)))
+ {
+ return; // aready imported
+ }
+ final Module module = getModuleOrLibraryByName(moduleName);
+ if (modules.containsKey(module.name()))
+ {
+ return; // aready imported, once again, in case some discrepancies in names?
+ }
modules.put(module.name(), module);
- ModuleData data = new ModuleData(module);
+ final ModuleData data = new ModuleData(module);
initializeModuleGlobals(data);
moduleData.put(module, data);
runModuleCode(c, module);
@@ -144,20 +159,21 @@ public abstract class ScriptHost
//modules.remove(module.getName());
//throw new InternalExpressionException("Failed to import a module "+moduleName);
}
- public void importNames(Context c, Module targetModule, String sourceModuleName, List identifiers )
+
+ public void importNames(final Context c, final Module targetModule, final String sourceModuleName, final List identifiers)
{
if (!moduleData.containsKey(targetModule))
{
throw new InternalExpressionException("Cannot import to module that doesn't exist");
}
- Module source = modules.get(sourceModuleName);
- ModuleData sourceData = moduleData.get(source);
- ModuleData targetData = moduleData.get(targetModule);
+ final Module source = modules.get(sourceModuleName);
+ final ModuleData sourceData = moduleData.get(source);
+ final ModuleData targetData = moduleData.get(targetModule);
if (sourceData == null || targetData == null)
{
throw new InternalExpressionException("Cannot import from module that is not imported");
}
- for (String identifier: identifiers)
+ for (final String identifier : identifiers)
{
if (sourceData.globalFunctions.containsKey(identifier))
{
@@ -174,10 +190,10 @@ public abstract class ScriptHost
}
}
- public Stream availableImports(String moduleName)
+ public Stream availableImports(final String moduleName)
{
- Module source = modules.get(moduleName);
- ModuleData sourceData = moduleData.get(source);
+ final Module source = modules.get(moduleName);
+ final ModuleData sourceData = moduleData.get(source);
if (sourceData == null)
{
throw new InternalExpressionException("Cannot import from module that is not imported");
@@ -192,136 +208,195 @@ public abstract class ScriptHost
protected abstract void runModuleCode(Context c, Module module); // this should be shell out in the executor
- public FunctionValue getFunction(String name) { return getFunction(main, name); }
- public FunctionValue getAssertFunction(Module module, String name)
+ public FunctionValue getFunction(final String name)
{
- FunctionValue ret = getFunction(module, name);
+ return getFunction(main, name);
+ }
+
+ public FunctionValue getAssertFunction(final Module module, final String name)
+ {
+ final FunctionValue ret = getFunction(module, name);
if (ret == null)
{
if (module == main)
- throw new InternalExpressionException("Function '"+name+"' is not defined yet");
+ {
+ throw new InternalExpressionException("Function '" + name + "' is not defined yet");
+ }
else
- throw new InternalExpressionException("Function '"+name+"' is not defined nor visible by its name in the imported module '"+module.name()+"'");
+ {
+ throw new InternalExpressionException("Function '" + name + "' is not defined nor visible by its name in the imported module '" + module.name() + "'");
+ }
}
return ret;
}
- private FunctionValue getFunction(Module module, String name)
+
+ private FunctionValue getFunction(final Module module, final String name)
{
- ModuleData local = getModuleData(module);
+ final ModuleData local = getModuleData(module);
FunctionValue ret = local.globalFunctions.get(name); // most uses would be from local scope anyways
- if (ret != null) return ret;
+ if (ret != null)
+ {
+ return ret;
+ }
ModuleData target = local.functionImports.get(name);
if (target != null)
{
ret = target.globalFunctions.get(name);
- if (ret != null) return ret;
+ if (ret != null)
+ {
+ return ret;
+ }
}
// not in local scope - will need to travel over import links
target = local.futureImports.get(name);
- if (target == null) return null;
+ if (target == null)
+ {
+ return null;
+ }
target = findModuleDataFromFunctionImports(name, target, 0);
- if (target == null) return null;
+ if (target == null)
+ {
+ return null;
+ }
local.futureImports.remove(name);
local.functionImports.put(name, target);
return target.globalFunctions.get(name);
}
- private ModuleData findModuleDataFromFunctionImports(String name, ModuleData source, int ttl)
+ private ModuleData findModuleDataFromFunctionImports(final String name, final ModuleData source, final int ttl)
{
- if (ttl > 64) throw new InternalExpressionException("Cannot import "+name+", either your imports are too deep or too loopy");
+ if (ttl > 64)
+ {
+ throw new InternalExpressionException("Cannot import " + name + ", either your imports are too deep or too loopy");
+ }
if (source.globalFunctions.containsKey(name))
+ {
return source;
+ }
if (source.functionImports.containsKey(name))
- return findModuleDataFromFunctionImports(name, source.functionImports.get(name), ttl+1);
+ {
+ return findModuleDataFromFunctionImports(name, source.functionImports.get(name), ttl + 1);
+ }
if (source.futureImports.containsKey(name))
- return findModuleDataFromFunctionImports(name, source.futureImports.get(name), ttl+1);
+ {
+ return findModuleDataFromFunctionImports(name, source.futureImports.get(name), ttl + 1);
+ }
return null;
}
- public LazyValue getGlobalVariable(String name) { return getGlobalVariable(main, name); }
- public LazyValue getGlobalVariable(Module module, String name)
+ public LazyValue getGlobalVariable(final String name)
{
- ModuleData local = getModuleData(module);
+ return getGlobalVariable(main, name);
+ }
+
+ public LazyValue getGlobalVariable(final Module module, final String name)
+ {
+ final ModuleData local = getModuleData(module);
LazyValue ret = local.globalVariables.get(name); // most uses would be from local scope anyways
- if (ret != null) return ret;
+ if (ret != null)
+ {
+ return ret;
+ }
ModuleData target = local.globalsImports.get(name);
if (target != null)
{
ret = target.globalVariables.get(name);
- if (ret != null) return ret;
+ if (ret != null)
+ {
+ return ret;
+ }
}
// not in local scope - will need to travel over import links
target = local.futureImports.get(name);
- if (target == null) return null;
+ if (target == null)
+ {
+ return null;
+ }
target = findModuleDataFromGlobalImports(name, target, 0);
- if (target == null) return null;
+ if (target == null)
+ {
+ return null;
+ }
local.futureImports.remove(name);
local.globalsImports.put(name, target);
return target.globalVariables.get(name);
}
- private ModuleData findModuleDataFromGlobalImports(String name, ModuleData source, int ttl)
+ private ModuleData findModuleDataFromGlobalImports(final String name, final ModuleData source, final int ttl)
{
- if (ttl > 64) throw new InternalExpressionException("Cannot import "+name+", either your imports are too deep or too loopy");
+ if (ttl > 64)
+ {
+ throw new InternalExpressionException("Cannot import " + name + ", either your imports are too deep or too loopy");
+ }
if (source.globalVariables.containsKey(name))
+ {
return source;
+ }
if (source.globalsImports.containsKey(name))
- return findModuleDataFromGlobalImports(name, source.globalsImports.get(name), ttl+1);
+ {
+ return findModuleDataFromGlobalImports(name, source.globalsImports.get(name), ttl + 1);
+ }
if (source.futureImports.containsKey(name))
- return findModuleDataFromGlobalImports(name, source.futureImports.get(name), ttl+1);
+ {
+ return findModuleDataFromGlobalImports(name, source.futureImports.get(name), ttl + 1);
+ }
return null;
}
- public void delFunctionWithPrefix(Module module, String prefix)
+ public void delFunctionWithPrefix(final Module module, final String prefix)
{
- ModuleData data = getModuleData(module);
+ final ModuleData data = getModuleData(module);
data.globalFunctions.entrySet().removeIf(e -> e.getKey().startsWith(prefix));
data.functionImports.entrySet().removeIf(e -> e.getKey().startsWith(prefix));
}
- public void delFunction(Module module, String funName)
+
+ public void delFunction(final Module module, final String funName)
{
- ModuleData data = getModuleData(module);
+ final ModuleData data = getModuleData(module);
data.globalFunctions.remove(funName);
data.functionImports.remove(funName);
}
- public void delGlobalVariableWithPrefix(Module module, String prefix)
+ public void delGlobalVariableWithPrefix(final Module module, final String prefix)
{
- ModuleData data = getModuleData(module);
+ final ModuleData data = getModuleData(module);
data.globalVariables.entrySet().removeIf(e -> e.getKey().startsWith(prefix));
data.globalsImports.entrySet().removeIf(e -> e.getKey().startsWith(prefix));
}
- public void delGlobalVariable(Module module, String varName)
+ public void delGlobalVariable(final Module module, final String varName)
{
- ModuleData data = getModuleData(module);
+ final ModuleData data = getModuleData(module);
data.globalFunctions.remove(varName);
data.functionImports.remove(varName);
}
- private ModuleData getModuleData(Module module)
+ private ModuleData getModuleData(final Module module)
{
- ModuleData data = moduleData.get(module);
- if (data == null) throw new IntegrityException("Module structure changed for the app. Did you reload the app with tasks running?");
+ final ModuleData data = moduleData.get(module);
+ if (data == null)
+ {
+ throw new IntegrityException("Module structure changed for the app. Did you reload the app with tasks running?");
+ }
return data;
}
- protected void assertAppIntegrity(Module module)
+ protected void assertAppIntegrity(final Module module)
{
getModuleData(module);
}
- public void addUserDefinedFunction(Context ctx, Module module, String name, FunctionValue fun)
+ public void addUserDefinedFunction(final Context ctx, final Module module, final String name, final FunctionValue fun)
{
getModuleData(module).globalFunctions.put(name, fun);
}
- public void setGlobalVariable(Module module, String name, LazyValue lv)
+ public void setGlobalVariable(final Module module, final String name, final LazyValue lv)
{
getModuleData(module).globalVariables.put(name, lv);
}
- public Stream globalVariableNames(Module module, Predicate predicate)
+ public Stream globalVariableNames(final Module module, final Predicate predicate)
{
return Stream.concat(Stream.concat(
getModuleData(module).globalVariables.keySet().stream(),
@@ -329,27 +404,33 @@ public abstract class ScriptHost
), getModuleData(module).futureImports.keySet().stream().filter(s -> s.startsWith("global_"))).filter(predicate);
}
- public Stream globalFunctionNames(Module module, Predicate predicate)
+ public Stream globalFunctionNames(final Module module, final Predicate predicate)
{
return Stream.concat(Stream.concat(
getModuleData(module).globalFunctions.keySet().stream(),
getModuleData(module).functionImports.keySet().stream()
- ),getModuleData(module).futureImports.keySet().stream().filter(s -> !s.startsWith("global_"))).filter(predicate);
+ ), getModuleData(module).futureImports.keySet().stream().filter(s -> !s.startsWith("global_"))).filter(predicate);
}
- public ScriptHost retrieveForExecution(String /*Nullable*/ user)
+ public ScriptHost retrieveForExecution(final String /*Nullable*/ user)
{
- if (!perUser) return this;
- ScriptHost oldUserHost = userHosts.get(user);
- if (oldUserHost != null) return oldUserHost;
- ScriptHost userHost = this.duplicate();
+ if (!perUser)
+ {
+ return this;
+ }
+ final ScriptHost oldUserHost = userHosts.get(user);
+ if (oldUserHost != null)
+ {
+ return oldUserHost;
+ }
+ final ScriptHost userHost = this.duplicate();
userHost.user = user;
this.setupUserHost(userHost);
userHosts.put(user, userHost);
return userHost;
}
- protected void setupUserHost(ScriptHost host)
+ protected void setupUserHost(final ScriptHost host)
{
// adding imports
host.modules.putAll(this.modules);
@@ -358,57 +439,65 @@ public abstract class ScriptHost
host.moduleData.forEach((module, data) -> data.setImportsBasedOn(host, this.moduleData.get(data.parent)));
}
- synchronized public void handleExpressionException(String msg, ExpressionException exc)
+ public synchronized void handleExpressionException(final String msg, final ExpressionException exc)
{
- System.out.println(msg+": "+exc);
+ System.out.println(msg + ": " + exc);
}
-
protected abstract ScriptHost duplicate();
- public Object getLock(Value name)
+ public Object getLock(final Value name)
{
- return locks.computeIfAbsent(name, (n) -> new Object());
+ return locks.computeIfAbsent(name, n -> new Object());
}
- public ThreadPoolExecutor getExecutor(Value pool)
+ public ThreadPoolExecutor getExecutor(final Value pool)
{
- if (inTermination) return null;
- return executorServices.computeIfAbsent(pool, (v) -> (ThreadPoolExecutor) Executors.newCachedThreadPool());
+ if (inTermination)
+ {
+ return null;
+ }
+ return executorServices.computeIfAbsent(pool, v -> (ThreadPoolExecutor) Executors.newCachedThreadPool());
}
public int taskCount()
{
return executorServices.values().stream().map(ThreadPoolExecutor::getActiveCount).reduce(0, Integer::sum);
}
- public int taskCount(Value pool)
+
+ public int taskCount(final Value pool)
{
- if (executorServices.containsKey(pool))
- {
- return executorServices.get(pool).getActiveCount();
- }
- return 0;
+ return executorServices.containsKey(pool) ? executorServices.get(pool).getActiveCount() : 0;
}
public void onClose()
{
inTermination = true;
executorServices.values().forEach(ThreadPoolExecutor::shutdown);
- for (ScriptHost uh : userHosts.values()) uh.onClose();
+ for (final ScriptHost uh : userHosts.values())
+ {
+ uh.onClose();
+ }
if (taskCount() > 0)
{
executorServices.values().forEach(e -> {
- ExecutorService stopper = Executors.newSingleThreadExecutor();
- stopper.submit( () -> {
- try {
+ final ExecutorService stopper = Executors.newSingleThreadExecutor();
+ stopper.submit(() -> {
+ try
+ {
// Wait a while for existing tasks to terminate
- if (!e.awaitTermination(1500, TimeUnit.MILLISECONDS)) {
+ if (!e.awaitTermination(1500, TimeUnit.MILLISECONDS))
+ {
e.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!e.awaitTermination(1500, TimeUnit.MILLISECONDS))
+ {
CarpetScriptServer.LOG.error("Failed to stop app's thread");
+ }
}
- } catch (InterruptedException ie) {
+ }
+ catch (final InterruptedException ie)
+ {
// (Re-)Cancel if current thread also interrupted
e.shutdownNow();
// Preserve interrupt status
@@ -421,12 +510,15 @@ public abstract class ScriptHost
}
}
- public void setPerPlayer(boolean isPerUser)
+ public void setPerPlayer(final boolean isPerUser)
{
perUser = isPerUser;
}
- public boolean isPerUser() {return perUser;}
+ public boolean isPerUser()
+ {
+ return perUser;
+ }
public Set getUserList()
{
@@ -436,21 +528,24 @@ public abstract class ScriptHost
public void resetErrorSnooper()
{
- errorSnooper=null;
+ errorSnooper = null;
}
public static final Logger DEPRECATION_LOG = LoggerFactory.getLogger("Scarpet Deprecation Warnings");
- public boolean issueDeprecation(String feature)
+ public boolean issueDeprecation(final String feature)
{
- if (deprecations.contains(feature)) return false;
+ if (deprecations.contains(feature))
+ {
+ return false;
+ }
deprecations.add(feature);
- DEPRECATION_LOG.warn("'"+feature+"' is deprecated and soon will be removed. Please consult the docs for their replacement");
+ DEPRECATION_LOG.warn("'" + feature + "' is deprecated and soon will be removed. Please consult the docs for their replacement");
return true;
}
- public ScriptServer scriptServer()
- {
- return scriptServer;
- }
+ public ScriptServer scriptServer()
+ {
+ return scriptServer;
+ }
}
diff --git a/src/main/java/carpet/script/ScriptServer.java b/src/main/java/carpet/script/ScriptServer.java
index 24e36383..5d13d024 100644
--- a/src/main/java/carpet/script/ScriptServer.java
+++ b/src/main/java/carpet/script/ScriptServer.java
@@ -6,6 +6,7 @@ import java.util.concurrent.ConcurrentHashMap;
import carpet.script.value.Value;
// WIP
-public class ScriptServer {
+public class ScriptServer
+{
public final Map