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 9 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
209 changes: 209 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,209 @@
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.OperationInfo;
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;
private Operation<Object, Object, Object> operation = null;

@Override
public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) {
operator = PATTERNS.getInfo(matchedPattern);
base = exprs[0];
Class<?>[] baseAccepted = base.acceptChange(ChangeMode.SET);
if (baseAccepted == null) {
Skript.error("This expression cannot be operated on.");
return false;
}
operative = LiteralUtils.defendExpression(exprs[1]);
node = getParser().getNode();
Class<?> operativeType = operative.getReturnType();
Class<?> baseType = base.getReturnType();
// Ensure 'baseType' is referencing a non-array class
if (baseType.isArray())
baseType = baseType.getComponentType();
if (operativeType.equals(Object.class) && baseType.equals(Object.class)) {
// Both are object, so we should do the checks within '#execute'
return LiteralUtils.canInitSafely(operative);
} else if (operativeType.equals(Object.class) || baseType.equals(Object.class)) {
// One is 'Object', so we can atleast see if the other has any operations registered
Class<?>[] returnTypes = null;
if (baseType.equals(Object.class)) {
returnTypes = Arithmetics.getOperations(operator).stream()
.filter(info -> info.getRight().isAssignableFrom(operativeType))
.map(OperationInfo::getReturnType)
.toArray(Class[]::new);
if (returnTypes.length == 0) {
Skript.error(operator.getName() + " cannot be performed with "
+ Utils.a(getClassInfoCodeName(operativeType)));
return false;
}
} else {
returnTypes = Arithmetics.getOperations(operator, baseType).stream()
.map(OperationInfo::getReturnType)
.toArray(Class[]::new);
if (returnTypes.length == 0) {
Skript.error("This expression can not be " + getOperatorString() + ".");
return false;
}
}
} else {
// We've deduced that the return types from both 'base' and 'operative' are guaranteed not to be 'Object.class'
// We can check to see if an operation exists, if not, parse error
operation = getOperation(baseType, operativeType);
if (operation == null) {
Skript.error("This expression cannot be " + getOperatorString() + " by "
+ Utils.a(getClassInfoCodeName(operativeType)) + ".");
return false;
}
}
return LiteralUtils.canInitSafely(operative);
}

@Override
protected void execute(Event event) {
Object operativeObject = operative.getSingle(event);
if (operativeObject == null)
return;
// Ensure 'operativeType' is not 'Object.class' by using '#getReturnType' or the class of the object
Class<?> operativeType = operative.getReturnType().equals(Object.class) ? operativeObject.getClass() : operative.getReturnType();
Operation<Object, Object, Object> operation = this.operation;
Function<?, Object> changerFunction = null;
Class<?> baseType = base.getReturnType();
// Convert array classes to singular, allowing for easier checks
if (baseType.isArray())
baseType = baseType.getComponentType();
// If 'base' is single or the '#getReturnType' returns a non 'Object.class' we can use the same operation
if (base.isSingle() || !baseType.equals(Object.class)) {
if (operation == null) {
Object baseObject = base.getSingle(event);
if (baseObject == null)
return;
// If we reached here through 'base.isSingle()', need to ensure the class is not 'Object.class'
baseType = baseType.equals(Object.class) ? baseObject.getClass() : baseType;
operation = getOperation(baseType, operativeType);
if (operation == null) {
error(Utils.A(getClassInfoCodeName(baseType)) + " cannot be " + getOperatorString()
+ " with " + Utils.a(getClassInfoCodeName(operativeType)) + ".");
return;
}
}
Operation<Object, Object, Object> finalOperation = operation;
changerFunction = object -> finalOperation.calculate(object, operativeObject);
} else {
changerFunction = object -> {
Operation<Object, Object, Object> thisOperation = getOperation(object.getClass(), operativeType);
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);
}

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

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

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
142 changes: 142 additions & 0 deletions src/test/skript/tests/syntaxes/effects/EffOperations.sk
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
test "operations effect numbers by literal numbers":
set {_num} to 1
multiply {_num} by 15
assert {_num} is 15 with "Failed multiplication for single number by literal number"
divide {_num} by 5
assert {_num} is 3 with "Failed division for single number by literal number"
raise {_num} to the power of 2
assert {_num} is 9 with "Failed exponentiation for single number by literal 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 by literal number"
divide {_nums::*} by 5
assert {_nums::*} is (4, 6, 8 and 10) with "Failed division for number list by literal number"
raise {_nums::*} to the power of 2
assert {_nums::*} is (16, 36, 64 and 100) with "Failed exponentiation for number list by literal number"

test "operations effect numbers by variable numbers":
set {_num} to 1
set {_multiply} to 10
set {_divide} to 5
set {_raise} to 2
multiply {_num} by {_multiply}
assert {_num} is 10 with "Failed multiplication for single number by variable number"
divide {_num} by {_divide}
assert {_num} is 2 with "Failed division for single number by variable number"
raise {_num} to the power of {_raise}
assert {_num} is 4 with "Failed exponentiation for single number by variable number"

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

test "operations effect vectors by function 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 function vector"
divide {_vector} by vector(2,3,4)
assert {_vector} is vector(2,2,2) with "Failed division for single vector by function 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 function 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 function vector"

test "operations effect vectors by variable vectors":
set {_vector} to vector(1,1,1)
set {_multiply} to vector(10,20,30)
set {_divide} to vector(5,5,5)
multiply {_vector} by {_multiply}
assert {_vector} is vector(10,20,30) with "Failed multiplication for single vector by vector"
divide {_vector} by {_divide}
assert {_vector} is vector(2,4,6) 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 {_multiply}
assert {_vectors::*} is (vector(20,40,60), vector(30,60,90) and vector(40,80,120)) with "Failed multiplication for vector list by variable vector"
divide {_vectors::*} by {_divide}
assert {_vectors::*} is (vector(4,8,12), vector(6,12,18) and vector(8,16,24)) with "Failed division for vector list by variable vector"

test "operations effect vectors by literal 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 literal number"
divide {_vector} by 2
assert {_vector} is vector(5,5,5) with "Failed division for single vector by literal 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 literal 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 literal number"

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

set {_vectors::*} to vector(2,2,2), vector(3,3,3) and vector(4,4,4)
multiply {_vectors::*} by {_multiply}
assert {_vectors::*} is (vector(30,30,30), vector(45,45,45) and vector(60,60,60)) with "Failed multiplication for vector list by variable number"
divide {_vectors::*} by {_divide}
assert {_vectors::*} is (vector(10,10,10), vector(15,15,15) and vector(20,20,20)) with "Failed division for vector list by variable number"

test "operations effect timespans by literal numbers":
set {_timespan} to 1 hour
multiply {_timespan} by 4
assert {_timespan} is 4 hours with "Failed multiplication for single timespan by literal number"
divide {_timespan} by 2
assert {_timespan} is 2 hours with "Failed division for single timespan by literal 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 literal 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 literal number"

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

set {_timespans::*} to (1 minute), (5 minutes) and (10 minutes)
multiply {_timespans::*} by {_multiply}
assert {_timespans::*} is ((6 minutes), (30 minutes) and (60 minutes)) with "Failed multiplication for timespan list by variable number"
divide {_timespans::*} by {_divide}
assert {_timespans::*} is ((3 minutes), (15 minutes) and (30 minutes)) with "Failed division for timespan list by variable number"

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

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

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

test "operations effect expression errors":
parse:
multiply (the hunger level of (random element out of all players)) by 1 hour
assert last parse logs contains "This expression cannot be multiplied by a timespan." with "Hunger level should not be able to be multiplied by timespan"

parse:
divide all worlds by 2
assert last parse logs contains "This expression cannot be operated on." with "ExprWorlds should not have a 'SET' ChangeMode"