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

Parse Effect #7520

Open
wants to merge 17 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
2 changes: 1 addition & 1 deletion src/main/java/ch/njol/skript/classes/Changer.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public boolean supportsKeyedChange() {

/**
* @param what The objects to change
* @param delta An array with one or more instances of one or more of the the classes returned by {@link #acceptChange(ChangeMode)} for the given change mode (null for
* @param delta An array with one or more instances of one or more of the classes returned by {@link #acceptChange(ChangeMode)} for the given change mode (null for
* {@link ChangeMode#DELETE} and {@link ChangeMode#RESET}). <b>This can be a Object[], thus casting is not allowed.</b>
* @param mode The {@link ChangeMode} to test.
* @throws UnsupportedOperationException (optional) if this method was called on an unsupported ChangeMode.
Expand Down
120 changes: 120 additions & 0 deletions src/main/java/ch/njol/skript/effects/EffParse.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
package ch.njol.skript.effects;

import ch.njol.skript.Skript;
import ch.njol.skript.classes.Changer.ChangeMode;
import ch.njol.skript.classes.Changer.ChangerUtils;
import ch.njol.skript.classes.ClassInfo;
import ch.njol.skript.classes.Parser;
import ch.njol.skript.doc.Description;
import ch.njol.skript.doc.Examples;
import ch.njol.skript.doc.Name;
import ch.njol.skript.doc.Since;
import ch.njol.skript.expressions.ExprParseError;
import ch.njol.skript.lang.*;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.skript.log.ParseLogHandler;
import ch.njol.util.Kleenean;
import org.bukkit.event.Event;
import org.jetbrains.annotations.Nullable;

@Name("Parse")
@Description("Parses a string or a list of strings as a type. If \"try to\" is used, the value won't be deleted if the parse fails.")
@Examples({"set {_a::*} to \"1\", \"2a\", \"3\", \"4c\", \"5\"",
"parse {_a::*} as integer",
"send {_a::*} # would send 1, 3 and 5",
"send last parse errors # would print errors about 2a and 4c"
})
@Since("INSERT VERSION")
public class EffParse extends Effect {

static {
Skript.registerEffect(EffParse.class, "[try:try to] parse %~strings% as %*classinfo%");
}

private Expression<String> toParse;
private ClassInfo<?> classInfo;
private boolean tryTo;

@Override
@SuppressWarnings("unchecked")
public boolean init(Expression<?>[] expressions, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) {
tryTo = parseResult.hasTag("try");
toParse = (Expression<String>) expressions[0];
classInfo = ((Literal<ClassInfo<?>>) expressions[1]).getSingle();

if (!toParse.getAnd()) {
Skript.error("Can't use 'or' lists in a parse effect");
return false;
}

if (classInfo.getC() == String.class) {
Skript.error("Parsing as text is useless as only things that are already text may be parsed");
return false;
}

Parser<?> parser = classInfo.getParser();
if (parser == null || !parser.canParse(ParseContext.PARSE)) {
Skript.error("Text cannot be parsed as " + classInfo.getName().withIndefiniteArticle());
return false;
}

if (toParse instanceof ExpressionList<String> toParseExpressions) {
for (int i = 0; i < toParseExpressions.getAllExpressions().size(); i++) {
Expression<String> expression = (Expression<String>) toParseExpressions.getAllExpressions().get(i);
if (!ChangerUtils.acceptsChange(expression, ChangeMode.SET, classInfo.getC())) {
Skript.error(toParse + " can't be set to " + classInfo.getName().withIndefiniteArticle());
return false;
}
}
} else if (!ChangerUtils.acceptsChange(toParse, ChangeMode.SET, classInfo.getC())) {
Skript.error(toParse + " can't be set to " + classInfo.getName().withIndefiniteArticle());
return false;
}

return true;
}

@Override
@SuppressWarnings("unchecked")
protected void execute(Event event) {
Parser<?> parser = classInfo.getParser();
assert parser != null; // checked in init()
ExprParseError.clearErrors();

ParseLogHandler parseLogHandler = new ParseLogHandler().start();
try {
if (toParse instanceof ExpressionList<String> toParseExpressions) {
for (int i = 0; i < toParseExpressions.getAllExpressions().size(); i++) {
Expression<String> expression = (Expression<String>) toParseExpressions.getAllExpressions().get(i);
expression.changeInPlace(event, stringToParse -> {
Object parsed = parser.parse(stringToParse, ParseContext.PARSE);
if (parsed == null) {
ExprParseError.addError(stringToParse + " could not be parsed as " + classInfo.getName().withIndefiniteArticle());
parseLogHandler.clearError();
return tryTo ? stringToParse : null;
}
return parsed;
});
}
} else {
toParse.changeInPlace(event, stringToParse -> {
Object parsed = parser.parse(stringToParse, ParseContext.PARSE);
if (parsed == null) {
ExprParseError.addError(stringToParse + " could not be parsed as " + classInfo.getName().withIndefiniteArticle());
return tryTo ? stringToParse : null;
}
return parsed;
});
}
} finally {
parseLogHandler.clear();
parseLogHandler.printLog();
}
}

@Override
public String toString(@Nullable Event event, boolean debug) {
return (tryTo ? "try to " : "") + "parse " + toParse + " as " + classInfo.getName().withIndefiniteArticle();
}

}
11 changes: 4 additions & 7 deletions src/main/java/ch/njol/skript/expressions/ExprParse.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,6 @@ public class ExprParse extends SimpleExpression<Object> {
"%string% parsed as (%-*classinfo%|\"<.*>\")");
}

@Nullable
static String lastError = null;

@SuppressWarnings("NotNullFieldNotInitialized")
private Expression<String> text;

Expand Down Expand Up @@ -149,7 +146,7 @@ protected Object[] get(Event event) {

ParseLogHandler parseLogHandler = SkriptLogger.startParseLogHandler();
try {
lastError = null;
ExprParseError.clearErrors();

if (classInfo != null) {
Parser<?> parser = classInfo.getParser();
Expand Down Expand Up @@ -209,12 +206,12 @@ protected Object[] get(Event event) {

LogEntry error = parseLogHandler.getError();
if (error != null) {
lastError = error.toString();
ExprParseError.addError(error.toString());
} else {
if (classInfo != null) {
lastError = text + " could not be parsed as " + classInfo.getName().withIndefiniteArticle();
ExprParseError.addError(text + " could not be parsed as " + classInfo.getName().withIndefiniteArticle());
} else {
lastError = text + " could not be parsed as \"" + pattern + "\"";
ExprParseError.addError(text + " could not be parsed as \"" + pattern + "\"");
}
}
return null;
Expand Down
28 changes: 25 additions & 3 deletions src/main/java/ch/njol/skript/expressions/ExprParseError.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
import ch.njol.skript.lang.util.SimpleExpression;
import ch.njol.util.Kleenean;

import java.util.ArrayList;
import java.util.List;

/**
* @author Peter Güttinger
*/
Expand All @@ -27,23 +30,34 @@
" message \"&lt;red&gt;Please put an integer on line 1!\""})
@Since("2.0")
public class ExprParseError extends SimpleExpression<String> {

static {
Skript.registerExpression(ExprParseError.class, String.class, ExpressionType.SIMPLE, "[the] [last] [parse] error");
Skript.registerExpression(ExprParseError.class, String.class, ExpressionType.SIMPLE, "[the] [last] [parse] error[all:s]");
}

private static final List<String> lastErrors = new ArrayList<>();
private boolean allErrors = false;

@Override
public boolean init(final Expression<?>[] exprs, final int matchedPattern, final Kleenean isDelayed, final ParseResult parseResult) {
allErrors = parseResult.hasTag("all");
return true;
}

@Override
protected String[] get(final Event e) {
return ExprParse.lastError == null ? new String[0] : new String[] {ExprParse.lastError};
if (lastErrors.isEmpty())
return new String[0];

if (allErrors)
return lastErrors.toArray(new String[0]);

return new String[] { lastErrors.getLast() };
}

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

@Override
Expand All @@ -55,5 +69,13 @@ public Class<? extends String> getReturnType() {
public String toString(final @Nullable Event e, final boolean debug) {
return "the last parse error";
}

public static void addError(String error) {
lastErrors.add(error);
}

public static void clearErrors() {
lastErrors.clear();
}

}
37 changes: 37 additions & 0 deletions src/test/skript/tests/syntaxes/effects/EffParse.sk
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
test "parse effect":
# test single value
set {_value} to "5"
parse {_value} as int
assert {_value} = 5 with "couldn't parse a single value"

set {_value} to "a"
try to parse {_value} as int
assert {_value} is set with "using 'try to' still deletes the value"

parse {_value} as int
assert {_value} isn't set with "failed parse didn't delete the value"

# test lists
set {_values::*} to "1", "2a", "3", "4b"
parse {_values::*} as int
assert {_values::1} = 1 with "couldn't parse a list - 1"
assert {_values::2} isn't set with "couldn't parse a list - 2"
assert {_values::3} = 3 with "couldn't parse a list - 3"
assert {_values::4} isn't set with "couldn't parse a list - 4"
assert size of (last parse errors) is 2 with "parse errors aren't set"

# test multiple expressions
set {_a} to "3"
set {_b} to "hello"
set {_c} to "5"
parse {_a}, {_b} and {_c} as int
assert {_a} = 3 with "couldn't parse multiple expressions - 1"
assert {_b} isn't set with "couldn't parse multiple expressions - 2"
assert {_c} = 5 with "couldn't parse multiple expressions - 3"

# test if lists keep their indices
set {_a::a} to "3"
set {_a::b} to "5"
parse {_a::*} as integer
assert {_a::a} = 3 with "lists didn't keep their indices - 1"
assert {_a::b} = 5 with "lists didn't keep their indices - 2"