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

For each index & value loop. #6562

Merged
merged 10 commits into from
Dec 18, 2024
1 change: 1 addition & 0 deletions src/main/java/ch/njol/skript/registrations/Feature.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
* Experimental feature toggles as provided by Skript itself.
*/
public enum Feature implements Experiment {
FOR_EACH_LOOPS("for loop", LifeCycle.EXPERIMENTAL, "for [each] [loop[s]]")
APickledWalrus marked this conversation as resolved.
Show resolved Hide resolved
Moderocky marked this conversation as resolved.
Show resolved Hide resolved
;

private final String codeName;
Expand Down
172 changes: 172 additions & 0 deletions src/main/java/ch/njol/skript/sections/SecFor.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
/**
* This file is part of Skript.
* <p>
* Skript is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* Skript is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with Skript. If not, see <http://www.gnu.org/licenses/>.
* <p>
* Copyright Peter Güttinger, SkriptLang team and contributors
*/
Moderocky marked this conversation as resolved.
Show resolved Hide resolved
package ch.njol.skript.sections;

import ch.njol.skript.Skript;
import ch.njol.skript.SkriptAPIException;
import ch.njol.skript.classes.Changer;
import ch.njol.skript.config.SectionNode;
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.lang.Expression;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.skript.lang.TriggerItem;
import ch.njol.skript.lang.Variable;
import ch.njol.skript.lang.util.ContainerExpression;
import ch.njol.skript.registrations.Feature;
import ch.njol.skript.util.Container;
import ch.njol.skript.util.Container.ContainerType;
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;
import java.util.Map;

@Name("For Each Loop (Experimental)")
@Description("""
A specialised loop section run for each element in a list.
Unlike the basic loop, this is designed for extracting the key & value from pairs.
The loop element's key/index and value can be stored in a variable for convenience.

When looping a simple (non-indexed) set of values, e.g. all players, the index will be the loop counter number."""
)
@Examples({
"for each {_player} in players:",
"\tsend \"Hello %{_player}%!\" to {_player}",
"",
"loop {_item} in {list of items::*}:",
"\tbroadcast {_item}'s name",
"",
"for each key {_index} in {list of items::*}:",
"\tbroadcast {_index}",
"",
"loop key {_index} and value {_value} in {list of items::*}:",
"\tbroadcast \"%{_index}% = %{_value}%\"",
"",
"for each {_index} = {_value} in {my list::*}:",
"\tbroadcast \"%{_index}% = %{_value}%\"",
})
@Since("INSERT VERSION")
public class SecFor extends SecLoop {

static {
Skript.registerSection(SecFor.class,
"(for [each]|loop) [value] %~object% in %objects%",
"(for [each]|loop) (key|index) %~object% in %objects%",
"(for [each]|loop) [key|index] %~object% (=|and) [value] %~object% in %objects%"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure about this = syntax. Is there a reason you chose it?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it was either from one of the issues/discussions suggesting this or I was copying from some other language, It's been about six months and I can't really remember.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh I remember, I think there was a worry about {x} and {y} being confusingly-ambiguous (not in terms of parsing but for a user to read, maybe thinking it was looping two items at a time) between a regular list of expressions and this specific syntax where the and is literally part of it, and we wanted a less-ambiguous alternative that emphasised the keys were mapped to the values.
I'd rather it wasn't a symbol (=) although I don't mind it, but I couldn't think of a better single word for it.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should avoid symbols if possible. I don't think for each {_a} = {_b} in {_c::*} is great.
In fact, we might want to require the usage of the keywords key|index and value for this option. for each {_a} and {_b} in {_c::*} makes it seem like c is holding some sort of tuple.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm fine with getting rid of =, how would you feel about , as an alternative? Python has e.g. for key, value in dict.items() and that's not terrible IMO.
I'm just worried that writing out the whole for key {blah} and value {blah} in ... is going to be more verbose than is necessary, when really we just need tome way to indicate one is the index representing the other.

Copy link
Member

@APickledWalrus APickledWalrus Dec 3, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That would certainly be a better shorthand than =. I am okay with it, though I dont think for {_key} and {_value} in ... is too bad

);
}

private @Nullable Expression<?> keyStore, valueStore;

@Override
@SuppressWarnings("unchecked")
public boolean init(Expression<?>[] exprs,
int matchedPattern,
Kleenean isDelayed,
ParseResult parseResult,
SectionNode sectionNode,
List<TriggerItem> triggerItems) {
if (!this.getParser().hasExperiment(Feature.FOR_EACH_LOOPS))
return false;
//<editor-fold desc="Set the key/value expressions based on the pattern" defaultstate="collapsed">
Comment on lines +73 to +74
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
return false;
//<editor-fold desc="Set the key/value expressions based on the pattern" defaultstate="collapsed">
return false;
//<editor-fold desc="Set the key/value expressions based on the pattern" defaultstate="collapsed">

switch (matchedPattern) {
case 0:
this.valueStore = exprs[0];
this.expression = LiteralUtils.defendExpression(exprs[1]);
break;
case 1:
this.keyStore = exprs[0];
this.expression = LiteralUtils.defendExpression(exprs[1]);
break;
default:
this.keyStore = exprs[0];
this.valueStore = exprs[1];
this.expression = LiteralUtils.defendExpression(exprs[2]);
}
//</editor-fold>
Moderocky marked this conversation as resolved.
Show resolved Hide resolved
//<editor-fold desc="Check our input expressions are safe/correct" defaultstate="collapsed">
if (!(keyStore instanceof Variable || keyStore == null)) {
Moderocky marked this conversation as resolved.
Show resolved Hide resolved
Skript.error("The 'key' input for a for-loop must be a variable to store the value.");
return false;
}
if (!(valueStore instanceof Variable || valueStore == null)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (!(valueStore instanceof Variable || valueStore == null)) {
if (valueStore != null && !(valueStore instanceof Variable)) {

Just to bring it in line with the keyStore check (and I think this is clearer)

Comment on lines +94 to +95
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
}
if (!(valueStore instanceof Variable || valueStore == null)) {
}
if (!(valueStore instanceof Variable || valueStore == null)) {

Skript.error("The 'value' input for a for-loop must be a variable to store the value.");
return false;
}
if (!LiteralUtils.canInitSafely(expression)) {
Comment on lines +98 to +99
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
}
if (!LiteralUtils.canInitSafely(expression)) {
}
if (!LiteralUtils.canInitSafely(expression)) {

Skript.error("Can't understand this loop: '" + parseResult.expr + "'");
return false;
}
if (Container.class.isAssignableFrom(expression.getReturnType())) {
Comment on lines +102 to +103
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
}
if (Container.class.isAssignableFrom(expression.getReturnType())) {
}
if (Container.class.isAssignableFrom(expression.getReturnType())) {

ContainerType type = expression.getReturnType().getAnnotation(ContainerType.class);
if (type == null)
throw new SkriptAPIException(expression.getReturnType()
.getName() + " implements Container but is missing the required @ContainerType annotation");
this.expression = new ContainerExpression((Expression<? extends Container<?>>) expression, type.value());
}
if (expression.isSingle()) {
Skript.error("Can't loop '" + expression + "' because it's only a single value");
return false;
}
//</editor-fold>
this.loadOptionalCode(sectionNode);
super.setNext(this);
return true;
}

@Override
protected void store(Event event, Object next) {
super.store(event, next);
//<editor-fold desc="Store the loop index/value in the variables" defaultstate="collapsed">
if (next instanceof Map.Entry) {
@SuppressWarnings("unchecked") Map.Entry<String, Object> entry = (Map.Entry<String, Object>) next;
Moderocky marked this conversation as resolved.
Show resolved Hide resolved
if (keyStore != null)
this.keyStore.change(event, new Object[] {entry.getKey()}, Changer.ChangeMode.SET);
if (valueStore != null)
this.valueStore.change(event, new Object[] {entry.getValue()}, Changer.ChangeMode.SET);
} else {
if (keyStore != null)
this.keyStore.change(event, new Object[] {this.getLoopCounter(event)}, Changer.ChangeMode.SET);
if (valueStore != null)
this.valueStore.change(event, new Object[] {next}, Changer.ChangeMode.SET);
}
//</editor-fold>
}

@Override
public String toString(@Nullable Event event, boolean debug) {
if (keyStore != null && valueStore != null) {
Moderocky marked this conversation as resolved.
Show resolved Hide resolved
return "for each key " + keyStore.toString(event, debug)
+ " and value " + valueStore.toString(event, debug) + " in "
+ super.expression.toString(event, debug);
} else if (keyStore != null) {
return "for each key " + keyStore.toString(event, debug)
+ " in " + super.expression.toString(event, debug);
}
assert valueStore != null : "How did we get here?";
return "for each value " + valueStore.toString(event, debug)
+ " in " + super.expression.toString(event, debug);
}

}
47 changes: 26 additions & 21 deletions src/main/java/ch/njol/skript/sections/SecLoop.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@
import ch.njol.skript.util.LiteralUtils;
import ch.njol.util.Kleenean;
import org.bukkit.event.Event;
import org.eclipse.jdt.annotation.Nullable;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.UnknownNullability;

import java.util.Iterator;
import java.util.List;
Expand Down Expand Up @@ -86,14 +87,13 @@ public class SecLoop extends LoopSection {
Skript.registerSection(SecLoop.class, "loop %objects%");
}

@SuppressWarnings("NotNullFieldNotInitialized")
private Expression<?> expr;
protected @UnknownNullability Expression<?> expression;

private final transient Map<Event, Object> current = new WeakHashMap<>();
private final transient Map<Event, Iterator<?>> currentIter = new WeakHashMap<>();
private final transient Map<Event, Iterator<?>> iteratorMap = new WeakHashMap<>();

@Nullable
private TriggerItem actualNext;
protected TriggerItem actualNext;

@Override
@SuppressWarnings("unchecked")
Expand All @@ -103,21 +103,21 @@ public boolean init(Expression<?>[] exprs,
ParseResult parseResult,
SectionNode sectionNode,
List<TriggerItem> triggerItems) {
expr = LiteralUtils.defendExpression(exprs[0]);
if (!LiteralUtils.canInitSafely(expr)) {
this.expression = LiteralUtils.defendExpression(exprs[0]);
if (!LiteralUtils.canInitSafely(expression)) {
Skript.error("Can't understand this loop: '" + parseResult.expr.substring(5) + "'");
return false;
}

if (Container.class.isAssignableFrom(expr.getReturnType())) {
ContainerType type = expr.getReturnType().getAnnotation(ContainerType.class);
if (Container.class.isAssignableFrom(expression.getReturnType())) {
ContainerType type = expression.getReturnType().getAnnotation(ContainerType.class);
if (type == null)
throw new SkriptAPIException(expr.getReturnType().getName() + " implements Container but is missing the required @ContainerType annotation");
expr = new ContainerExpression((Expression<? extends Container<?>>) expr, type.value());
throw new SkriptAPIException(expression.getReturnType().getName() + " implements Container but is missing the required @ContainerType annotation");
this.expression = new ContainerExpression((Expression<? extends Container<?>>) expression, type.value());
}

if (expr.isSingle()) {
Skript.error("Can't loop '" + expr + "' because it's only a single value");
if (expression.isSingle()) {
Skript.error("Can't loop '" + expression + "' because it's only a single value");
return false;
}

Expand All @@ -130,12 +130,12 @@ public boolean init(Expression<?>[] exprs,
@Override
@Nullable
protected TriggerItem walk(Event event) {
Iterator<?> iter = currentIter.get(event);
Iterator<?> iter = iteratorMap.get(event);
if (iter == null) {
iter = expr instanceof Variable ? ((Variable<?>) expr).variablesIterator(event) : expr.iterator(event);
iter = expression instanceof Variable ? ((Variable<?>) expression).variablesIterator(event) : expression.iterator(event);
if (iter != null) {
if (iter.hasNext())
currentIter.put(event, iter);
iteratorMap.put(event, iter);
else
iter = null;
}
Expand All @@ -145,15 +145,20 @@ protected TriggerItem walk(Event event) {
debug(event, false);
return actualNext;
} else {
current.put(event, iter.next());
currentLoopCounter.put(event, (currentLoopCounter.getOrDefault(event, 0L)) + 1);
Object next = iter.next();
this.store(event, next);
return walk(event, true);
}
}

protected void store(Event event, Object next) {
this.current.put(event, next);
this.currentLoopCounter.put(event, (currentLoopCounter.getOrDefault(event, 0L)) + 1);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
this.currentLoopCounter.put(event, (currentLoopCounter.getOrDefault(event, 0L)) + 1);
this.currentLoopCounter.put(event, currentLoopCounter.getOrDefault(event, 0L) + 1);

The parentheses use seems a bit odd here

}

@Override
public String toString(@Nullable Event event, boolean debug) {
return "loop " + expr.toString(event, debug);
return "loop " + expression.toString(event, debug);
}

@Nullable
Expand All @@ -162,7 +167,7 @@ public Object getCurrent(Event event) {
}

public Expression<?> getLoopedExpression() {
return expr;
return expression;
}

@Override
Expand All @@ -180,7 +185,7 @@ public TriggerItem getActualNext() {
@Override
public void exit(Event event) {
current.remove(event);
currentIter.remove(event);
iteratorMap.remove(event);
super.exit(event);
}

Expand Down
61 changes: 61 additions & 0 deletions src/test/skript/tests/syntaxes/sections/SecFor.sk
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
using for each loops

test "for section":

set {_list::*} to 1, 5, and 10
set {_expect} to 0
for {_value} in {_list::*}:
assert {_value} is greater than 0 with "Expected value > 0, found %{_value}%"
set {_expect} to {_value}

assert {_value} is 10 with "Expected value = 10, found %{_value}%"
assert {_expect} is 10 with "Expected expect = 10, found %{_expect}%"

delete {_key}
delete {_value}

for {_key} = {_value} in {_list::*}:
assert {_key} is greater than 0 with "Expected key > 0, found %{_key}%"
assert {_key} is less than 4 with "Expected key < 4, found %{_key}%"
assert {_value} is greater than 0 with "Expected value > 0, found %{_value}%"

assert {_key} is 3 with "Expected key = 3, found %{_key}%"
assert {_value} is 10 with "Expected value = 10, found %{_value}%"

delete {_key}
delete {_value}


for key {_key} and value {_value} in {_list::*}:
assert {_key} is greater than 0 with "Expected key > 0, found %{_key}%"
assert {_key} is less than 4 with "Expected key < 4, found %{_key}%"
assert {_value} is greater than 0 with "Expected value > 0, found %{_value}%"

assert {_key} is 3 with "Expected key = 3, found %{_key}%"
assert {_value} is 10 with "Expected value = 10, found %{_value}%"

delete {_key}
delete {_value}

for {_key} and {_value} in {_list::*}:
assert {_key} is greater than 0 with "Expected key > 0, found %{_key}%"
assert {_key} is less than 4 with "Expected key < 4, found %{_key}%"
assert {_value} is greater than 0 with "Expected value > 0, found %{_value}%"

assert {_key} is 3 with "Expected key = 3, found %{_key}%"
assert {_value} is 10 with "Expected value = 10, found %{_value}%"

delete {_key}
delete {_value}

# 'loop' syntax alternative
loop {_key} and {_value} in {_list::*}:
assert {_key} is greater than 0 with "Expected key > 0, found %{_key}%"
assert {_key} is less than 4 with "Expected key < 4, found %{_key}%"
assert {_value} is greater than 0 with "Expected value > 0, found %{_value}%"

assert {_key} is 3 with "Expected key = 3, found %{_key}%"
assert {_value} is 10 with "Expected value = 10, found %{_value}%"

delete {_key}
delete {_value}