Skip to content
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

Improve ExprElement #5478

Merged
merged 19 commits into from
Jan 1, 2024
Merged
Show file tree
Hide file tree
Changes from 11 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
180 changes: 125 additions & 55 deletions src/main/java/ch/njol/skript/expressions/ExprElement.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,87 +29,142 @@
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.skript.lang.util.SimpleExpression;
import ch.njol.skript.util.LiteralUtils;
import ch.njol.skript.util.Patterns;
import ch.njol.util.Kleenean;
import ch.njol.util.StringUtils;
import ch.njol.util.coll.CollectionUtils;
import com.google.common.collect.Iterators;
import org.apache.commons.lang.ArrayUtils;
import org.bukkit.event.Event;
import org.eclipse.jdt.annotation.Nullable;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

@Name("Element of")
@Description({"The first, last or a random element of a set, e.g. a list variable.",
"See also: <a href='#ExprRandom'>random</a>"})
@Examples("give a random element out of {free items::*} to the player")
@Since("2.0, 2.7 (relative to last element)")
import java.util.List;

@Name("Elements")
@Description({
"The first, last, range or a random element of a set, e.g. a list variable.",
"See also: <a href='#ExprRandom'>random</a>"
UnderscoreTud marked this conversation as resolved.
Show resolved Hide resolved
})
@Examples("broadcast the first 3 elements of {top players::*}")
@Since("2.0, 2.7 (relative to last element), INSERT VERSION (range of elements)")
public class ExprElement extends SimpleExpression<Object> {

private static final Patterns<ElementType[]> PATTERNS = new Patterns<>(new Object[][]{
{"[the] (first|:last) element [out] of %objects%", new ElementType[] {ElementType.FIRST_ELEMENT, ElementType.LAST_ELEMENT}},
{"[the] (first|:last) %number% elements [out] of %objects%", new ElementType[] {ElementType.FIRST_X_ELEMENTS, ElementType.LAST_X_ELEMENTS}},
{"[a] random element [out] of %objects%", new ElementType[] {ElementType.RANDOM}},
{"[the] %number%(st|nd|rd|th) [last:[to] last] element [out] of %objects%", new ElementType[] {ElementType.ORDINAL, ElementType.TAIL_END_ORDINAL}},
{"[the] elements (from|between) %number% (to|and) %number% [out] of %objects%", new ElementType[] {ElementType.RANGE}}
UnderscoreTud marked this conversation as resolved.
Show resolved Hide resolved
});

static {
Skript.registerExpression(ExprElement.class, Object.class, ExpressionType.PROPERTY, "(0:[the] first|1:[the] last|2:[a] random|3:[the] %-number%(st|nd|rd|th)|4:[the] %-number%(st|nd|rd|th) [to] last) element [out] of %objects%");
Skript.registerExpression(ExprElement.class, Object.class, ExpressionType.PROPERTY, PATTERNS.getPatterns());
}

private enum ElementType {
FIRST, LAST, RANDOM, ORDINAL, TAIL_END_ORDINAL
FIRST_ELEMENT,
LAST_ELEMENT,
FIRST_X_ELEMENTS,
LAST_X_ELEMENTS,
RANDOM,
ORDINAL,
TAIL_END_ORDINAL,
RANGE
}

private ElementType type;

private Expression<?> expr;

@Nullable
private Expression<Number> number;
private @Nullable Expression<Number> startIndex, endIndex;
private ElementType type;

@Override
@SuppressWarnings("unchecked")
public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) {
expr = LiteralUtils.defendExpression(exprs[2]);
type = ElementType.values()[parseResult.mark];
number = (Expression<Number>) (type == ElementType.ORDINAL ? exprs[0]: exprs[1]);
ElementType[] types = PATTERNS.getInfo(matchedPattern);
expr = LiteralUtils.defendExpression(exprs[exprs.length - 1]);
switch (types[0]) {
case RANGE:
UnderscoreTud marked this conversation as resolved.
Show resolved Hide resolved
endIndex = (Expression<Number>) exprs[1];
//$FALL-THROUGH$
case FIRST_X_ELEMENTS:
case ORDINAL:
startIndex = (Expression<Number>) exprs[0];
break;
default:
startIndex = null;
break;
}
type = types[parseResult.hasTag("last") ? 1 : 0];
return LiteralUtils.canInitSafely(expr);
}

@Override
@Nullable
@SuppressWarnings("unchecked, rawtypes")
protected Object[] get(Event event) {
Iterator<?> iter = expr.iterator(event);
if (iter == null || !iter.hasNext())
Iterator<?> iterator = expr.iterator(event);
if (iterator == null || !iterator.hasNext())
return null;
Object element = null;
int startIndex = 0;
int endIndex = 0;
if (this.startIndex != null) {
Number number = this.startIndex.getSingle(event);
if (number == null)
return null;
startIndex = number.intValue();
if (startIndex <= 0 && type != ElementType.RANGE)
return null;
}
if (this.endIndex != null) {
Number number = this.endIndex.getSingle(event);
if (number == null)
return null;
endIndex = number.intValue();
}
switch (type) {
case FIRST:
element = iter.next();
case FIRST_ELEMENT:
element = iterator.next();
break;
case LAST_ELEMENT:
element = Iterators.getLast(iterator);
break;
case LAST:
element = Iterators.getLast(iter);
case RANDOM:
Object[] allElements = Iterators.toArray(iterator, Object.class);
element = CollectionUtils.getRandom(allElements);
break;
case ORDINAL:
assert this.number != null;
Number number = this.number.getSingle(event);
if (number == null)
return null;
try {
element = Iterators.get(iter, number.intValue() - 1);
} catch (IndexOutOfBoundsException exception) {
Iterators.advance(iterator, startIndex - 1);
if (!iterator.hasNext())
return null;
}
break;
case RANDOM:
Object[] allIterValues = Iterators.toArray(iter, Object.class);
element = CollectionUtils.getRandom(allIterValues);
element = iterator.next();
break;
case TAIL_END_ORDINAL:
allIterValues = Iterators.toArray(iter, Object.class);
assert this.number != null;
number = this.number.getSingle(event);
if (number == null)
allElements = Iterators.toArray(iterator, Object.class);
if (startIndex > allElements.length)
return null;
int ordinal = number.intValue();
if (ordinal <= 0 || ordinal > allIterValues.length)
return null;
element = allIterValues[allIterValues.length - ordinal];
element = allElements[allElements.length - startIndex];
break;
case FIRST_X_ELEMENTS:
return Iterators.toArray((Iterator) Iterators.limit(iterator, startIndex), getReturnType());
case LAST_X_ELEMENTS:
allElements = Iterators.toArray((Iterator) iterator, getReturnType());
startIndex = Math.min(startIndex, allElements.length);
return ArrayUtils.subarray(allElements, allElements.length - startIndex, allElements.length);
case RANGE:
allElements = Iterators.toArray((Iterator) iterator, getReturnType());
boolean reverse = startIndex > endIndex;
int from = Math.min(startIndex, endIndex) - 1;
int to = Math.max(startIndex, endIndex);
from = Math.max(from, 0);
to = Math.min(Math.max(to, 0), allElements.length);
Object[] elements = ArrayUtils.subarray(allElements, from, to);
if (reverse)
ArrayUtils.reverse(elements);
UnderscoreTud marked this conversation as resolved.
Show resolved Hide resolved
return elements;
}
Object[] elementArray = (Object[]) Array.newInstance(getReturnType(), 1);
elementArray[0] = element;
Expand All @@ -125,15 +180,16 @@ public <R> Expression<? extends R> getConvertedExpression(Class<R>... to) {
return null;

ExprElement exprElement = new ExprElement();
exprElement.type = this.type;
exprElement.expr = convExpr;
exprElement.number = this.number;
exprElement.startIndex = startIndex;
exprElement.endIndex = this.endIndex;
exprElement.type = this.type;
return (Expression<? extends R>) exprElement;
}

@Override
public boolean isSingle() {
return true;
return type != ElementType.FIRST_X_ELEMENTS && type != ElementType.LAST_X_ELEMENTS && type != ElementType.RANGE;
}

@Override
Expand All @@ -142,36 +198,50 @@ public Class<?> getReturnType() {
}

@Override
public String toString(@Nullable Event e, boolean debug) {
String prefix;
public String toString(@Nullable Event event, boolean debug) {
String prefix = "";
switch (type) {
case FIRST:
case FIRST_ELEMENT:
prefix = "the first";
break;
case LAST:
case LAST_ELEMENT:
prefix = "the last";
break;
case FIRST_X_ELEMENTS:
assert startIndex != null;
prefix = "the first " + startIndex.toString(event, debug);
break;
case LAST_X_ELEMENTS:
assert startIndex != null;
prefix = "the last " + startIndex.toString(event, debug);
break;
case RANDOM:
prefix = "a random";
break;
case ORDINAL:
assert number != null;
case TAIL_END_ORDINAL:
assert startIndex != null;
prefix = "the ";
// Proper ordinal number
if (number instanceof Literal) {
Number number = ((Literal<Number>) this.number).getSingle();
if (startIndex instanceof Literal) {
Number number = ((Literal<Number>) startIndex).getSingle();
if (number == null)
prefix += this.number.toString(e, debug) + "th";
prefix += startIndex.toString(event, debug) + "th";
else
prefix += StringUtils.fancyOrderNumber(number.intValue());
} else {
prefix += number.toString(e, debug) + "th";
prefix += startIndex.toString(event, debug) + "th";
}
if (type == ElementType.TAIL_END_ORDINAL)
prefix += " last";
break;
case RANGE:
assert startIndex != null && endIndex != null;
return "the elements from " + startIndex.toString(event, debug) + " to " + endIndex.toString(event, debug) + " of " + expr.toString(event, debug);
default:
throw new IllegalStateException();
TheLimeGlass marked this conversation as resolved.
Show resolved Hide resolved
}
return prefix + " element of " + expr.toString(e, debug);
return prefix + (isSingle() ? " element" : " elements") + " of " + expr.toString(event, debug);
}

}
13 changes: 13 additions & 0 deletions src/test/skript/tests/syntaxes/expressions/ExprElement.sk
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,16 @@ test "ExprElement":
assert 1st last element of {_list::*} is "foobar" with "Incorrect 1st last element"
assert 0th last element of {_list::*} is not set with "Incorrect 0th last element"
assert -1th last element of {_list::*} is not set with "Incorrect -1th element"
assert first 2 elements of {_list::*} are "foo" or "bar" with "Incorrect first 2 elements"
assert first -1 elements of {_list::*} is not set with "Incorrect first -1 elements"
assert first 5 elements of {_list::*} are "foo", "bar" or "foobar" with "Incorrect first 5 elements"
assert last 2 elements of {_list::*} are "bar" or "foobar" with "Incorrect last 2 elements"
assert last -1 elements of {_list::*} is not set with "Incorrect last -1 elements"
assert last 5 elements of {_list::*} are "foo", "bar" or "foobar" with "Incorrect last 5 elements"
assert elements from 1 to 2 of {_list::*} are "foo" or "bar" with "Incorrect elements from 1 to 2"
assert elements from 2 to 1 of {_list::*} are "foo" or "bar" with "Incorrect elements from 2 to 1"
assert elements from 2 to 3 of {_list::*} are "bar" or "foobar" with "Incorrect elements from 2 to 3"
assert elements from 3 to 3 of {_list::*} is "foobar" with "Incorrect elements from 3 to 3"
assert elements from -1 to 4 of {_list::*} are "foo", "bar" or "foobar" with "Incorrect elements from -1 to 4"
assert elements from 5 to 5 of {_list::*} is not set with "Incorrect elements from 5 to 5"
assert elements from 1 to 1 of {_list::*} is "foo" with "Incorrect elements from 1 to 1"
UnderscoreTud marked this conversation as resolved.
Show resolved Hide resolved