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 6 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
171 changes: 171 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,171 @@
package ch.njol.skript.effects;

import ch.njol.skript.Skript;
import ch.njol.skript.classes.ClassInfo;
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.lang.Variable;
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). Cannot use literals.")
@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
""")
@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 instanceof Variable<?>)) {
Skript.error("Cannot operate on a non variable object.");
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;
ClassInfo<?> operativeClassInfo = Classes.getSuperClassInfo(operativeObject.getClass());
Class<?> operativeClass = operativeClassInfo.getC();
Operation<Object, Object, Object> operation = null;
Function<?, Object> function = 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;
ClassInfo<?> baseClassInfo = Classes.getSuperClassInfo(baseObject.getClass());
Class<?> baseClass = baseClassInfo.getC();
if (!baseClass.equals(operativeClass)) {
operation = getOperation(baseClass, operativeClass);
if (operation == null) {
error(Utils.A(baseClassInfo.getCodeName()) + "cannot be " + getOperatorString()
+ " with " + Utils.a(operativeClassInfo.getCodeName()));
return;
}
} else {
operation = getOperation(operativeClass);
if (operation == null) {
error(Utils.A(operativeClassInfo.getCodeName()) + " cannot be " + getOperatorString() + ".");
return;
}
}
Operation<Object, Object, Object> finalOperation = operation;
function = 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
function = 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) function);
}

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

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

@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 @@ -123,6 +123,59 @@ public static <L, R, T> Operation<L, R, T> getOperation(Operator operator, Class
return info == null ? null : info.getOperation();
}

/**
* @see #getConvertedOperation(Operator, Class, Class, Class)
*/
public static <L> @Nullable Operation<L, L, L> getConvertedOperation(Operator operator, Class<L> type) {
return getConvertedOperation(operator, type, type, type);
}

/**
* @see #getConvertedOperation(Operator, Class, Class, Class)
*/
public static <L, R> @Nullable Operation<L, R, ?> getConvertedOperation(Operator operator, Class<L> leftClass, Class<R> rightClass) {
return getConvertedOperation(operator, leftClass, rightClass, leftClass);
}

/**
* <p>
* This method attempts to convert all parameters
* i.e. {@code leftClass}, {@code rightClass} and {@code returnType}
* into the expected operation.
* </p>
*/
public static <L, R, T> @Nullable Operation<L, R, T> getConvertedOperation(
Operator operator,
Class<L> leftClass,
Class<R> rightClass,
Class<T> returnType
) {
OperationInfo<L, R, T> exactInfo = getOperationInfo(operator, leftClass, rightClass, returnType);
if (exactInfo != null)
return exactInfo.getOperation();
OperationInfo<?, ?, ?> closestInfo = null;
for (OperationInfo<?, ?, ?> info : getOperations(operator)) {
if (info.getLeft().isAssignableFrom(leftClass)
&& info.getRight().isAssignableFrom(rightClass)
&& info.getReturnType().isAssignableFrom(returnType)
) {
if (closestInfo == null || (
closestInfo.getLeft().isAssignableFrom(info.getLeft())
&& closestInfo.getRight().isAssignableFrom(info.getRight())
&& closestInfo.getReturnType().isAssignableFrom(info.getReturnType()))
) {
closestInfo = info;
}
}
}
if (closestInfo == null)
return null;
//noinspection unchecked
Operation<L, R, T> convertedOperation = (Operation<L, R, T>) closestInfo.getOperation();
getOperations_i(operator).add(new OperationInfo<>(leftClass, rightClass, returnType, convertedOperation));
return convertedOperation;
}

@Nullable
public static <L, R, T> OperationInfo<L, R, T> lookupOperationInfo(Operator operator, Class<L> leftClass, Class<R> rightClass, Class<T> returnType) {
OperationInfo<L, R, ?> info = lookupOperationInfo(operator, leftClass, rightClass);
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 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 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 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 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 error":
parse:
multiply 1 by 2
assert last parse logs is set with "Operations should only work for variables - multiplication"

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

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