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

Refactor ExprFilter to use new parser data API #6342

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
217 changes: 63 additions & 154 deletions src/main/java/ch/njol/skript/expressions/ExprFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,83 +27,72 @@
import ch.njol.skript.lang.Condition;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.ExpressionType;
import ch.njol.skript.lang.Literal;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.skript.lang.parser.ParserInstance;
import ch.njol.skript.lang.util.SimpleExpression;
import org.skriptlang.skript.lang.converter.Converters;
import ch.njol.skript.util.LiteralUtils;
import ch.njol.skript.util.Utils;
import ch.njol.util.Kleenean;
import ch.njol.util.coll.iterator.ArrayIterator;
import com.google.common.collect.Iterators;
import org.bukkit.event.Event;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

@Name("Filter")
@Description("Filters a list based on a condition. " +
"For example, if you ran 'broadcast \"something\" and \"something else\" where [string input is \"something\"]', " +
"only \"something\" would be broadcast as it is the only string that matched the condition.")
@Description({
"Filters a list based on a condition. ",
"For example, if you ran 'broadcast \"something\" and \"something else\" where [string input is \"something\"]', ",
"only \"something\" would be broadcast as it is the only string that matched the condition."
})
@Examples("send \"congrats on being staff!\" to all players where [player input has permission \"staff\"]")
@Since("2.2-dev36")
@SuppressWarnings({"null", "unchecked"})
public class ExprFilter extends SimpleExpression<Object> {

@Nullable
private static ExprFilter parsing;

static {
Skript.registerExpression(ExprFilter.class, Object.class, ExpressionType.COMBINED,
"%objects% (where|that match) \\[<.+>\\]");
ParserInstance.registerData(FilterData.class, FilterData::new);
}

private Object current;
private List<ExprInput<?>> children = new ArrayList<>();
private Condition condition;
private String rawCond;
private Expression<Object> objects;
private Condition filterCondition;
private String unparsedCondition;
private Expression<?> unfilteredObjects;
private Set<ExprFilterInput<?>> dependentInputs = new HashSet<>();
Pikachu920 marked this conversation as resolved.
Show resolved Hide resolved

@Nullable
public static ExprFilter getParsing() {
return parsing;
}
private Object currentFilterValue;

@Override
public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) {
try {
parsing = this;
objects = LiteralUtils.defendExpression(exprs[0]);
if (objects.isSingle())
return false;
rawCond = parseResult.regexes.get(0).group();
condition = Condition.parse(rawCond, "Can't understand this condition: " + rawCond);
} finally {
parsing = null;
}
return condition != null && LiteralUtils.canInitSafely(objects);
unfilteredObjects = LiteralUtils.defendExpression(exprs[0]);
if (unfilteredObjects.isSingle() || !LiteralUtils.canInitSafely(unfilteredObjects))
return false;
unparsedCondition = parseResult.regexes.get(0).group();
FilterData filterData = getParser().getData(FilterData.class);
ExprFilter originalParentFilter = filterData.parentFilter;
filterData.parentFilter = this;
filterCondition = Condition.parse(unparsedCondition, "Can't understand this condition: " + unparsedCondition);
filterData.parentFilter = originalParentFilter;
return filterCondition != null;
}

@NonNull
@Override
public Iterator<?> iterator(Event event) {
Iterator<?> objIterator = this.objects.iterator(event);
if (objIterator == null)
Iterator<?> unfilteredObjectIterator = unfilteredObjects.iterator(event);
if (unfilteredObjectIterator == null)
return Collections.emptyIterator();
try {
return Iterators.filter(objIterator, object -> {
current = object;
return condition.check(event);
});
} finally {
current = null;
}
return Iterators.filter(unfilteredObjectIterator, candidateObject -> {
currentFilterValue = candidateObject;
return filterCondition.check(event);
});
}

@Override
Expand All @@ -115,146 +104,66 @@ protected Object[] get(Event event) {
}
}

public Object getCurrent() {
return current;
}

private void addChild(ExprInput<?> child) {
children.add(child);
}

private void removeChild(ExprInput<?> child) {
children.remove(child);
}

@Override
public Class<?> getReturnType() {
return objects.getReturnType();
return unfilteredObjects.getReturnType();
}

@Override
public boolean isSingle() {
return objects.isSingle();
return false;
}

@Override
public String toString(Event event, boolean debug) {
return String.format("%s where [%s]", objects.toString(event, debug), rawCond);
return unfilteredObjects.toString(event, debug) + " that match [" + unparsedCondition + "]";
}

@Override
public boolean isLoopOf(String s) {
for (ExprInput<?> child : children) { // if they used player input, let's assume loop-player is valid
if (child.getClassInfo() == null || child.getClassInfo().getUserInputPatterns() == null)
continue;
private boolean matchesAnySpecifiedTypes(String candidateString) {
for (ExprFilterInput<?> dependentInput : dependentInputs) {
ClassInfo<?> specifiedType = dependentInput.getSpecifiedType();
if (specifiedType == null)
return false;
Pattern[] specifiedTypePatterns = specifiedType.getUserInputPatterns();
if (specifiedTypePatterns == null)
return false;

for (Pattern pattern : child.getClassInfo().getUserInputPatterns()) {
if (pattern.matcher(s).matches())
for (Pattern typePattern : specifiedTypePatterns) {
if (typePattern.matcher(candidateString).matches()) {
return true;
}
}
}
return objects.isLoopOf(s); // nothing matched, so we'll rely on the object expression's logic
return false;
}

@Name("Filter Input")
@Description("Represents the input in a filter expression. " +
"For example, if you ran 'broadcast \"something\" and \"something else\" where [input is \"something\"]" +
"the condition would be checked twice, using \"something\" and \"something else\" as the inputs.")
@Examples("send \"congrats on being staff!\" to all players where [input has permission \"staff\"]")
@Since("2.2-dev36")
public static class ExprInput<T> extends SimpleExpression<T> {

static {
Skript.registerExpression(ExprInput.class, Object.class, ExpressionType.COMBINED,
"input",
"%*classinfo% input"
);
}

@Nullable
private final ExprInput<?> source;
private final Class<? extends T>[] types;
private final Class<T> superType;
@SuppressWarnings("NotNullFieldNotInitialized")
private ExprFilter parent;
@Nullable
private ClassInfo<?> inputType;

public ExprInput() {
this(null, (Class<? extends T>) Object.class);
}

public ExprInput(@Nullable ExprInput<?> source, Class<? extends T>... types) {
this.source = source;
if (source != null) {
this.parent = source.parent;
this.inputType = source.inputType;
parent.removeChild(source);
parent.addChild(this);
}

this.types = types;
this.superType = (Class<T>) Utils.getSuperType(types);
}

@Override
public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) {
parent = ExprFilter.getParsing();

if (parent == null)
return false;

parent.addChild(this);
inputType = matchedPattern == 0 ? null : ((Literal<ClassInfo<?>>) exprs[0]).getSingle();
return true;
}

@Override
protected T[] get(Event event) {
Object current = parent.getCurrent();
if (inputType != null && !inputType.getC().isInstance(current)) {
return null;
}

try {
return Converters.convert(new Object[]{current}, types, superType);
} catch (ClassCastException e1) {
return (T[]) Array.newInstance(superType, 0);
}
}

public void setParent(ExprFilter parent) {
this.parent = parent;
}
@Override
public boolean isLoopOf(String candidateString) {
return unfilteredObjects.isLoopOf(candidateString) || matchesAnySpecifiedTypes(candidateString);
}

@Override
public <R> Expression<? extends R> getConvertedExpression(Class<R>... to) {
return new ExprInput<>(this, to);
}
public Set<ExprFilterInput<?>> getDependentInputs() {
return dependentInputs;
Pikachu920 marked this conversation as resolved.
Show resolved Hide resolved
}

@Override
public Expression<?> getSource() {
return source == null ? this : source;
}
@Nullable
public Object getCurrentFilterValue() {
return currentFilterValue;
}

@Override
public Class<? extends T> getReturnType() {
return superType;
}
public static class FilterData extends ParserInstance.Data {

@Nullable
private ClassInfo<?> getClassInfo() {
return inputType;
}
private ExprFilter parentFilter;

@Override
public boolean isSingle() {
return true;
public FilterData(ParserInstance parserInstance) {
super(parserInstance);
}

@Override
public String toString(Event event, boolean debug) {
return inputType == null ? "input" : inputType.getCodeName() + " input";
@Nullable
public ExprFilter getParentFilter() {
return parentFilter;
}

}
Expand Down
Loading