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

API for custom default values during parsing. #7256

Open
wants to merge 2 commits into
base: dev/feature
Choose a base branch
from
Open
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
17 changes: 16 additions & 1 deletion src/main/java/ch/njol/skript/lang/SkriptParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import ch.njol.skript.lang.function.ExprFunctionCall;
import ch.njol.skript.lang.function.FunctionReference;
import ch.njol.skript.lang.function.Functions;
import ch.njol.skript.lang.parser.DefaultValueData;
import ch.njol.skript.lang.parser.ParserInstance;
import ch.njol.skript.lang.util.SimpleLiteral;
import ch.njol.skript.localization.Language;
Expand Down Expand Up @@ -259,7 +260,16 @@ public boolean hasTag(String tag) {
}

private static @NotNull DefaultExpression<?> getDefaultExpression(ExprInfo exprInfo, String pattern) {
DefaultExpression<?> expr = exprInfo.classes[0].getDefaultExpression();
DefaultExpression<?> expr = null;
// check custom default values first.
DefaultValueData data = getParser().getData(DefaultValueData.class);
if (data != null)
expr = data.getDefaultValue(exprInfo.classes[0].getC());

// then check classinfo
if (expr == null)
expr = exprInfo.classes[0].getDefaultExpression();

if (expr == null)
throw new SkriptAPIException("The class '" + exprInfo.classes[0].getCodeName() + "' does not provide a default expression. Either allow null (with %-" + exprInfo.classes[0].getCodeName() + "%) or make it mandatory [pattern: " + pattern + "]");
if (!(expr instanceof Literal) && (exprInfo.flagMask & PARSE_EXPRESSIONS) == 0)
Expand Down Expand Up @@ -1416,6 +1426,11 @@ private static ParserInstance getParser() {
return ParserInstance.get();
}

// register default value data when the parser class is loaded.
static {
ParserInstance.registerData(DefaultValueData.class, DefaultValueData::new);
}

/**
* @deprecated due to bad naming conventions,
* use {@link #LIST_SPLIT_PATTERN} instead.
Expand Down
68 changes: 68 additions & 0 deletions src/main/java/ch/njol/skript/lang/parser/DefaultValueData.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package ch.njol.skript.lang.parser;

import ch.njol.skript.lang.DefaultExpression;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;

/**
* A Parser Data that stores custom default values that should be given preference over event-values and other
* traditional default values.
* <br>
* These do not apply to arithmetic or other dynamic default values, they're only supplied during parsing.
* @see ch.njol.skript.test.runner.SecCustomDefault SecCustomDefault for example usage
*/
public class DefaultValueData extends ParserInstance.Data {

private final Map<Class<?>, Deque<DefaultExpression<?>>> defaults = new HashMap<>();

public DefaultValueData(ParserInstance parserInstance) {
super(parserInstance);
}

/**
* Sets the default value for type to value.
* <br>
* Any custom default values should be removed after they go out of scope.
* It will not be done automatically.
*
* @see #removeDefaultValue(Class)
*
* @param type The class which this value applies to.
* @param value The value to use.
* @param <T> The class of this value.
*/
public <T> void addDefaultValue(Class<T> type, DefaultExpression<T> value) {
defaults.computeIfAbsent(type, (key) -> new ArrayDeque<>()).push(value);
}

/**
* Gets the default value for the given type.
* @param type The class which this value applies to.
* @param <T> The class of this value.
* @return The default value for type, or null if none is set.
*/
public <T> @Nullable DefaultExpression<T> getDefaultValue(Class<T> type) {
Deque<DefaultExpression<?>> stack = defaults.get(type);
if (stack == null || stack.isEmpty())
return null;
//noinspection unchecked
return (DefaultExpression<T>) stack.peek();
}

/**
* Removes a default value from the data.
* <br>
* Default values are handled using stacks, so be sure to remove only what you have added. Nothing more, nothing less.
* @param type Which class to remove the default value of.
*/
public void removeDefaultValue(Class<?> type) {
Deque<DefaultExpression<?>> stack = defaults.get(type);
if (stack != null && !stack.isEmpty())
stack.pop();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package ch.njol.skript.test.runner;

import ch.njol.skript.Skript;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.ExpressionType;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.skript.lang.util.SimpleExpression;
import ch.njol.util.Kleenean;
import org.bukkit.event.Event;
import org.jetbrains.annotations.Nullable;

public class ExprDefaultNumberValue extends SimpleExpression<Number> {

static {
if (TestMode.ENABLED)
Skript.registerExpression(ExprDefaultNumberValue.class, Number.class, ExpressionType.PROPERTY,
"default number [%number%]");
}

Expression<Number> value;

@Override
public boolean init(Expression<?>[] expressions, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) {
//noinspection unchecked
value = (Expression<Number>) expressions[0];
return true;
}

@Override
protected Number @Nullable [] get(Event event) {
return new Number[]{value.getSingle(event)};
}

@Override
public boolean isSingle() {
return true;
}

@Override
public Class<? extends Number> getReturnType() {
return Number.class;
}

@Override
public String toString(@Nullable Event event, boolean debug) {
return "default number";
}

}
72 changes: 72 additions & 0 deletions src/main/java/ch/njol/skript/test/runner/SecCustomDefault.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package ch.njol.skript.test.runner;

import ch.njol.skript.Skript;
import ch.njol.skript.classes.ClassInfo;
import ch.njol.skript.config.SectionNode;
import ch.njol.skript.lang.DefaultExpression;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.Literal;
import ch.njol.skript.lang.Section;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.skript.lang.TriggerItem;
import ch.njol.skript.lang.parser.DefaultValueData;
import ch.njol.skript.util.LiteralUtils;
import ch.njol.util.Kleenean;
import org.bukkit.event.Event;
import org.jetbrains.annotations.Nullable;

import java.util.List;

public class SecCustomDefault extends Section {

static {
if (TestMode.ENABLED) {
Skript.registerSection(SecCustomDefault.class, "run with custom default value %*object% for %*classinfo%");
}
}

Literal<?> value;
ClassInfo<?> type;

@Override
public boolean init(Expression<?>[] expressions, int matchedPattern, Kleenean isDelayed, ParseResult parseResult,
SectionNode sectionNode, List<TriggerItem> triggerItems) {
value = (Literal<?>) LiteralUtils.defendExpression(expressions[0]);
//noinspection unchecked
this.type = ((Literal<ClassInfo<?>>) expressions[1]).getSingle();
Class<?> type = this.type.getC();

if (!type.isAssignableFrom(value.getReturnType())) {
Skript.error("The value expression returns an invalid type: expected " + type.getSimpleName() +
", got " + value.getReturnType().getSimpleName());
return true;
}

DefaultValueData data = getParser().getData(DefaultValueData.class);
if (data == null)
throw new IllegalStateException("DefaultValueData did not exist");

// Add custom default value
//noinspection rawtypes,unchecked
data.addDefaultValue((Class) type, (DefaultExpression) value);

// parse section with custom value
loadCode(sectionNode);

// remove custom value
data.removeDefaultValue(type);

return true;
}

@Override
protected @Nullable TriggerItem walk(Event event) {
return walk(event, true);
}

@Override
public String toString(@Nullable Event event, boolean debug) {
return "run with custom default value " + value.toString(event, debug) + " for " + type.toString(event, debug);
}

}
8 changes: 8 additions & 0 deletions src/test/skript/tests/misc/custom default values.sk
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
test "custom default values":
run with custom default value 7 for number:
assert default number is 7 with "default value was not 7"
run with custom default value 3 for number:
assert default number is 3 with "default value was not 3"
assert default number is 7 with "default value was not 7"
assert default number is 1 with "default value was not 1"

Loading