Skip to content

EffOperations #7764

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 16 commits into
base: dev/feature
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
161 changes: 161 additions & 0 deletions src/main/java/ch/njol/skript/effects/EffOperations.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
package ch.njol.skript.effects;

import ch.njol.skript.Skript;
import ch.njol.skript.classes.Changer.ChangeMode;
import ch.njol.skript.config.Node;
import ch.njol.skript.doc.Description;
import ch.njol.skript.doc.Example;
import ch.njol.skript.doc.Name;
import ch.njol.skript.doc.Since;
import ch.njol.skript.lang.Effect;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.skript.lang.SyntaxStringBuilder;
import ch.njol.skript.registrations.Classes;
import ch.njol.skript.util.LiteralUtils;
import ch.njol.skript.util.Patterns;
import ch.njol.skript.util.Utils;
import ch.njol.util.Kleenean;
import org.bukkit.event.Event;
import org.jetbrains.annotations.Nullable;
import org.skriptlang.skript.lang.arithmetic.Arithmetics;
import org.skriptlang.skript.lang.arithmetic.Operation;
import org.skriptlang.skript.lang.arithmetic.Operator;
import org.skriptlang.skript.log.runtime.SyntaxRuntimeErrorProducer;

import java.util.function.Function;

@Name("Operations")
@Description("Perform multiplication, division, or exponentiation operations on variable objects "
+ "(i.e. numbers, vectors, timespans, and other objects from addons). "
+ "Literals cannot be used on the left-hand side.")
@Example("""
set {_num} to 1
multiply {_num} by 10
divide {_num} by 5
raise {_num} to the power of 2
""")
@Example("""
set {_nums::*} to 15, 21 and 30
divide {_nums::*} by 3
multiply {_nums::*} by 5
raise {_nums::*} to the power of 3
""")
@Example("""
set {_vector} to vector(1,1,1)
multiply {_vector} by vector(4,8,16)
divide {_vector} by 2
""")
@Example("""
set {_timespan} to 1 hour
multiply {_timespan} by 3
""")
@Example("""
# Will error due to literal
multiply 1 by 2
divide 10 by {_num}
""")
@Since("INSERT VERSION")
public class EffOperations extends Effect implements SyntaxRuntimeErrorProducer {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not EffArithmetic?


private static final Patterns<Operator> PATTERNS = new Patterns<>(new Object[][]{
{"multiply %~objects% by %object%", Operator.MULTIPLICATION},
{"divide %~objects% by %object%", Operator.DIVISION},
{"raise %~objects% to [the] (power|exponent) [of] %object%", Operator.EXPONENTIATION}
});

static {
Skript.registerEffect(EffOperations.class, PATTERNS.getPatterns());
}

private Operator operator;
private Expression<?> base;
private Expression<?> operative;
private Node node;

@Override
public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) {
operator = PATTERNS.getInfo(matchedPattern);
base = exprs[0];
if (base.acceptChange(ChangeMode.SET) == null) {
Skript.error("This expression cannot be operated on.");
return false;
}
operative = LiteralUtils.defendExpression(exprs[1]);
node = getParser().getNode();
return LiteralUtils.canInitSafely(operative);
}

@Override
protected void execute(Event event) {
Object operativeObject = operative.getSingle(event);
if (operativeObject == null)
return;
Class<?> operativeClass = operativeObject.getClass();
Operation<Object, Object, Object> operation = null;
Function<?, Object> changerFunction = null;
if (base.isSingle()) {
// If the variable provided is single, then we can do some checks
// to ensure an operation is available; if not, we can produce a proper error.
Object baseObject = base.getSingle(event);
if (baseObject == null)
return;
Class<?> baseClass = baseObject.getClass();
operation = getOperation(baseClass, operativeClass);
if (operation == null) {
error(Utils.A(getClassInfoCodeName(baseClass)) + " cannot be " + getOperatorString()
+ " with " + Utils.a(getClassInfoCodeName(operativeClass)));
return;
}
Operation<Object, Object, Object> finalOperation = operation;
changerFunction = object -> finalOperation.calculate(object, operativeObject);
} else {
// In the case of a list variable, we should probably ignore throwing multiple errors for each object
// that is not applicable for an operation
changerFunction = object -> {
Operation<Object, Object, Object> thisOperation = getOperation(object.getClass(), operativeClass);
if (thisOperation != null)
return thisOperation.calculate(object, operativeObject);
return object;
};
}
//noinspection unchecked,rawtypes
base.changeInPlace(event, (Function) changerFunction);
}

private @Nullable Operation<Object, Object, Object> getOperation(Class<?> leftClass, Class<?> rightClass) {
//noinspection unchecked
return (Operation<Object, Object, Object>) Arithmetics.getOperation(operator, leftClass, rightClass, leftClass);
}

private String getClassInfoCodeName(Class<?> clazz) {
return Classes.getSuperClassInfo(clazz).getCodeName();
}

@Override
public Node getNode() {
return node;
}

private String getOperatorString() {
return switch (operator) {
case MULTIPLICATION -> "multiplied";
case DIVISION -> "divided";
case EXPONENTIATION -> "exponentiated";
default -> "";
};
}

@Override
public String toString(@Nullable Event event, boolean debug) {
SyntaxStringBuilder builder = new SyntaxStringBuilder(event, debug);
switch (operator) {
case MULTIPLICATION -> builder.append("multiply", base, "by");
case DIVISION -> builder.append("divide", base, "by");
case EXPONENTIATION -> builder.append("raise", base, "to the power of");
}
builder.append(operative);
return builder.toString();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public static boolean operationExists(Operator operator, Class<?> leftClass, Cla
@SuppressWarnings("unchecked")
public static <L, R, T> OperationInfo<L, R, T> getOperationInfo(Operator operator, Class<L> leftClass, Class<R> rightClass, Class<T> returnType) {
OperationInfo<L, R, ?> info = getOperationInfo(operator, leftClass, rightClass);
if (info != null && returnType.isAssignableFrom(info.getReturnType()))
if (info != null && (returnType.isAssignableFrom(info.getReturnType()) || info.getReturnType().isAssignableFrom(returnType)))
return (OperationInfo<L, R, T>) info;
return null;
}
Expand Down
68 changes: 68 additions & 0 deletions src/test/skript/tests/syntaxes/effects/EffOperations.sk
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
test "operations effect numbers":
set {_num} to 1
multiply {_num} by 15
assert {_num} is 15 with "Failed multiplication for single number"
divide {_num} by 5
assert {_num} is 3 with "Failed division for single number"
raise {_num} to the power of 2
assert {_num} is 9 with "Failed exponentiation for single number"

set {_nums::*} to 2, 3, 4 and 5
multiply {_nums::*} by 10
assert {_nums::*} is (20, 30, 40 and 50) with "Failed multiplication for number list"
divide {_nums::*} by 5
assert {_nums::*} is (4, 6, 8 and 10) with "Failed division for number list"
raise {_nums::*} to the power of 2
assert {_nums::*} is (16, 36, 64 and 100) with "Failed exponentiation for number list"

test "operations effect vectors by vectors":
set {_vector} to vector(1,1,1)
multiply {_vector} by vector(4,6,8)
assert {_vector} is vector(4,6,8) with "Failed multiplication for single vector by vector"
divide {_vector} by vector(2,3,4)
assert {_vector} is vector(2,2,2) with "Failed division for single vector by vector"

set {_vectors::*} to vector(2,2,2), vector(3,3,3) and vector(4,4,4)
multiply {_vectors::*} by vector(2,5,10)
assert {_vectors::*} is (vector(4,10,20), vector(6,15,30) and vector(8,20,40)) with "Failed multiplication for vector list by vector"
divide {_vectors::*} by vector(1,5,5)
assert {_vectors::*} is (vector(4,2,4), vector(6,3,6) and vector(8,4,8)) with "Failed division for vector list by vector"

test "operations effect vectors by numbers":
set {_vector} to vector(1,1,1)
multiply {_vector} by 10
assert {_vector} is vector(10,10,10) with "Failed multiplication for single vector by number"
divide {_vector} by 2
assert {_vector} is vector(5,5,5) with "Failed division for single vector by number"

set {_vectors::*} to vector(2,2,2), vector(3,3,3) and vector(4,4,4)
multiply {_vectors::*} by 4
assert {_vectors::*} is (vector(8,8,8), vector(12,12,12) and vector(16,16,16)) with "Failed multiplication for vector list by number"
divide {_vectors::*} by 2
assert {_vectors::*} is (vector(4,4,4), vector(6,6,6) and vector(8,8,8)) with "Failed division for vector list by number"

test "operations effect timespans by numbers":
set {_timespan} to 1 hour
multiply {_timespan} by 4
assert {_timespan} is 4 hours with "Failed multiplication for single timespan by number"
divide {_timespan} by 2
assert {_timespan} is 2 hours with "Failed division for single timespan by number"

set {_timespans::*} to (1 minute), (5 minutes) and (10 minutes)
multiply {_timespans::*} by 5
assert {_timespans::*} is ((5 minutes), (25 minutes) and (50 minutes)) with "Failed multiplication for timespan list by number"
divide {_timespans::*} by 2
assert {_timespans::*} is ((2 minutes and 30 seconds), (12 minutes and 30 seconds) and (25 minutes)) with "Failed division for timespan list by number"

test "operations effect literals error":
parse:
multiply 1 by 2
assert last parse logs is set with "Operations should not work for literals - multiplication"

parse:
divide 20 by 4
assert last parse logs is set with "Operations should not work for literals - division"

parse:
raise 3 to the powwer of 100
assert last parse logs is set with "Operations should not work for literals - exponentiation"