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

Simple Structures #6551

Merged
Merged
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
80 changes: 51 additions & 29 deletions src/main/java/ch/njol/skript/ScriptLoader.java
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,10 @@
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.BlockingQueue;
Expand Down Expand Up @@ -490,17 +492,17 @@ private static CompletableFuture<ScriptInfo> loadScripts(List<Config> configs, O

ScriptInfo scriptInfo = new ScriptInfo();

List<NonNullPair<Script, List<Structure>>> scripts = new ArrayList<>();
List<LoadingScriptInfo> scripts = new ArrayList<>();

List<CompletableFuture<Void>> scriptInfoFutures = new ArrayList<>();
for (Config config : configs) {
if (config == null)
throw new NullPointerException();

CompletableFuture<Void> future = makeFuture(() -> {
NonNullPair<Script, List<Structure>> pair = loadScript(config);
scripts.add(pair);
scriptInfo.add(new ScriptInfo(1, pair.getSecond().size()));
LoadingScriptInfo info = loadScript(config);
scripts.add(info);
scriptInfo.add(new ScriptInfo(1, info.structures.size()));
return null;
}, openCloseable);

Expand All @@ -518,31 +520,32 @@ private static CompletableFuture<ScriptInfo> loadScripts(List<Config> configs, O

// build sorted list
// this nest of pairs is terrible, but we need to keep the reference to the modifiable structures list
List<NonNullPair<NonNullPair<Script, List<Structure>>, Structure>> pairs = scripts.stream()
.flatMap(pair -> { // Flatten each entry down to a stream of Script-Structure pairs
return pair.getSecond().stream()
.map(structure -> new NonNullPair<>(pair, structure));
List<NonNullPair<LoadingScriptInfo, Structure>> pairs = scripts.stream()
.flatMap(info -> { // Flatten each entry down to a stream of Script-Structure pairs
return info.structures.stream()
.map(structure -> new NonNullPair<>(info, structure));
})
.sorted(Comparator.comparing(pair -> pair.getSecond().getPriority()))
.collect(Collectors.toCollection(ArrayList::new));

// pre-loading
pairs.removeIf(pair -> {
LoadingScriptInfo loadingInfo = pair.getFirst();
Structure structure = pair.getSecond();

parser.setActive(pair.getFirst().getFirst());
parser.setActive(loadingInfo.script);
parser.setCurrentStructure(structure);
parser.setNode(structure.getEntryContainer().getSource());
parser.setNode(loadingInfo.nodeMap.get(structure));

try {
if (!structure.preLoad()) {
pair.getFirst().getSecond().remove(structure);
loadingInfo.structures.remove(structure);
return true;
}
} catch (Exception e) {
//noinspection ThrowableNotThrown
Skript.exception(e, "An error occurred while trying to preLoad a Structure.");
pair.getFirst().getSecond().remove(structure);
loadingInfo.structures.remove(structure);
return true;
}
return false;
Expand All @@ -556,21 +559,22 @@ private static CompletableFuture<ScriptInfo> loadScripts(List<Config> configs, O

// loading
pairs.removeIf(pair -> {
LoadingScriptInfo loadingInfo = pair.getFirst();
Structure structure = pair.getSecond();

parser.setActive(pair.getFirst().getFirst());
parser.setActive(loadingInfo.script);
parser.setCurrentStructure(structure);
parser.setNode(structure.getEntryContainer().getSource());
parser.setNode(loadingInfo.nodeMap.get(structure));

try {
if (!structure.load()) {
pair.getFirst().getSecond().remove(structure);
loadingInfo.structures.remove(structure);
return true;
}
} catch (Exception e) {
//noinspection ThrowableNotThrown
Skript.exception(e, "An error occurred while trying to load a Structure.");
pair.getFirst().getSecond().remove(structure);
loadingInfo.structures.remove(structure);
return true;
}
return false;
Expand All @@ -579,21 +583,22 @@ private static CompletableFuture<ScriptInfo> loadScripts(List<Config> configs, O

// post-loading
pairs.removeIf(pair -> {
LoadingScriptInfo loadingInfo = pair.getFirst();
Structure structure = pair.getSecond();

parser.setActive(pair.getFirst().getFirst());
parser.setActive(loadingInfo.script);
parser.setCurrentStructure(structure);
parser.setNode(structure.getEntryContainer().getSource());
parser.setNode(loadingInfo.nodeMap.get(structure));

try {
if (!structure.postLoad()) {
pair.getFirst().getSecond().remove(structure);
loadingInfo.structures.remove(structure);
return true;
}
} catch (Exception e) {
//noinspection ThrowableNotThrown
Skript.exception(e, "An error occurred while trying to postLoad a Structure.");
pair.getFirst().getSecond().remove(structure);
loadingInfo.structures.remove(structure);
return true;
}
return false;
Expand All @@ -612,17 +617,34 @@ private static CompletableFuture<ScriptInfo> loadScripts(List<Config> configs, O
});
}

private static class LoadingScriptInfo {

public final Script script;

public final List<Structure> structures;

public final Map<Structure, Node> nodeMap;

public LoadingScriptInfo(Script script, List<Structure> structures, Map<Structure, Node> nodeMap) {
this.script = script;
this.structures = structures;
this.nodeMap = nodeMap;
}

}

/**
* Creates a script and loads the provided config into it.
* @param config The config to load into a script.
* @return A pair containing the script that was loaded and a modifiable version of the structures list.
*/
// Whenever you call this method, make sure to also call PreScriptLoadEvent
private static NonNullPair<Script, List<Structure>> loadScript(Config config) {
private static LoadingScriptInfo loadScript(Config config) {
if (config.getFile() == null)
throw new IllegalArgumentException("A config must have a file to be loaded.");

ParserInstance parser = getParser();
Map<Structure, Node> nodeMap = new HashMap<>();
List<Structure> structures = new ArrayList<>();
Script script = new Script(config, structures);
parser.setActive(script);
Expand All @@ -632,31 +654,31 @@ private static NonNullPair<Script, List<Structure>> loadScript(Config config) {
SkriptConfig.configs.add(config);

try (CountingLogHandler ignored = new CountingLogHandler(SkriptLogger.SEVERE).start()) {
for (Node cnode : config.getMainNode()) {
if (!(cnode instanceof SectionNode)) {
Skript.error("invalid line - all code has to be put into triggers");
for (Node node : config.getMainNode()) {
if (!(node instanceof SimpleNode) && !(node instanceof SectionNode)) {
// unlikely to occur, but just in case
Skript.error("could not interpret line as a structure");
continue;
}

SectionNode node = ((SectionNode) cnode);
String line = node.getKey();
if (line == null)
continue;
line = replaceOptions(line); // replace options here before validation

if (!SkriptParser.validateLine(line))
continue;

if (Skript.logVeryHigh() && !Skript.debug())
Skript.info("loading trigger '" + line + "'");

line = replaceOptions(line);

Structure structure = Structure.parse(line, node, "Can't understand this structure: " + line);

if (structure == null)
continue;

structures.add(structure);
nodeMap.put(structure, node);
}

if (Skript.logHigh()) {
Expand Down Expand Up @@ -694,8 +716,8 @@ private static NonNullPair<Script, List<Structure>> loadScript(Config config) {
Skript.exception(e);
}
}
return new NonNullPair<>(script, structures);

return new LoadingScriptInfo(script, structures, nodeMap);
}

/*
Expand Down
7 changes: 7 additions & 0 deletions src/main/java/ch/njol/skript/Skript.java
Original file line number Diff line number Diff line change
Expand Up @@ -1515,6 +1515,13 @@ public static <E extends Structure> void registerStructure(Class<E> c, String...
structures.add(structureInfo);
}

public static <E extends Structure> void registerSimpleStructure(Class<E> c, String... patterns) {
checkAcceptRegistrations();
String originClassPath = Thread.currentThread().getStackTrace()[2].getClassName();
StructureInfo<E> structureInfo = new StructureInfo<>(patterns, c, originClassPath, true);
structures.add(structureInfo);
}

public static <E extends Structure> void registerStructure(Class<E> c, EntryValidator entryValidator, String... patterns) {
checkAcceptRegistrations();
String originClassPath = Thread.currentThread().getStackTrace()[2].getClassName();
Expand Down
10 changes: 7 additions & 3 deletions src/main/java/ch/njol/skript/lang/SkriptEvent.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ public abstract class SkriptEvent extends Structure {
public static final Priority PRIORITY = new Priority(600);

private String expr;
private SectionNode source;
@Nullable
protected EventPriority eventPriority;
@Nullable
Expand All @@ -67,7 +68,7 @@ public abstract class SkriptEvent extends Structure {
protected Trigger trigger;

@Override
public final boolean init(Literal<?>[] args, int matchedPattern, ParseResult parseResult, EntryContainer entryContainer) {
public final boolean init(Literal<?>[] args, int matchedPattern, ParseResult parseResult, @Nullable EntryContainer entryContainer) {
this.expr = parseResult.expr;

EventData eventData = getParser().getData(EventData.class);
Expand Down Expand Up @@ -101,6 +102,9 @@ public final boolean init(Literal<?>[] args, int matchedPattern, ParseResult par
return false;
}

assert entryContainer != null; // cannot be null for non-simple structures
this.source = entryContainer.getSource();

return init(args, matchedPattern, parseResult);
}

Expand Down Expand Up @@ -128,7 +132,7 @@ public boolean load() {
if (!shouldLoadEvent())
return false;

SectionNode source = getEntryContainer().getSource();
// noinspection ConstantConditions - entry container cannot be null as this structure is not simple
if (Skript.debug() || source.debug())
Skript.debug(expr + " (" + this + "):");

Expand All @@ -141,7 +145,7 @@ public boolean load() {
Script script = getParser().getCurrentScript();

trigger = new Trigger(script, expr, this, items);
int lineNumber = getEntryContainer().getSource().getLine();
int lineNumber = source.getLine();
trigger.setLineNumber(lineNumber); // Set line number for debugging
trigger.setDebugLabel(script + ": line " + lineNumber);
} finally {
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/ch/njol/skript/structures/StructAliases.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ public class StructAliases extends Structure {
}

@Override
public boolean init(Literal<?>[] args, int matchedPattern, ParseResult parseResult, EntryContainer entryContainer) {
public boolean init(Literal<?>[] args, int matchedPattern, ParseResult parseResult, @Nullable EntryContainer entryContainer) {
// noinspection ConstantConditions - entry container cannot be null as this structure is not simple
SectionNode node = entryContainer.getSource();
node.convertToEntries(0, "=");

Expand Down
9 changes: 6 additions & 3 deletions src/main/java/ch/njol/skript/structures/StructCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -143,20 +143,23 @@ protected Integer getValue(String value) {
);
}

@SuppressWarnings("NotNullFieldNotInitialized")
private EntryContainer entryContainer;

@Nullable
private ScriptCommand scriptCommand;

@Override
public boolean init(Literal<?>[] args, int matchedPattern, ParseResult parseResult, EntryContainer entryContainer) {
public boolean init(Literal<?>[] args, int matchedPattern, ParseResult parseResult, @Nullable EntryContainer entryContainer) {
assert entryContainer != null; // cannot be null for non-simple structures
this.entryContainer = entryContainer;
return true;
}

@Override
public boolean load() {
getParser().setCurrentEvent("command", ScriptCommandEvent.class);

EntryContainer entryContainer = getEntryContainer();

String fullCommand = entryContainer.getSource().getKey();
assert fullCommand != null;
fullCommand = ScriptLoader.replaceOptions(fullCommand);
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/ch/njol/skript/structures/StructEvent.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public class StructEvent extends Structure {

@Override
@SuppressWarnings("ConstantConditions")
public boolean init(Literal<?>[] args, int matchedPattern, ParseResult parseResult, EntryContainer entryContainer) {
public boolean init(Literal<?>[] args, int matchedPattern, ParseResult parseResult, @Nullable EntryContainer entryContainer) {
APickledWalrus marked this conversation as resolved.
Show resolved Hide resolved
String expr = parseResult.regexes.get(0).group();

EventData data = getParser().getData(EventData.class);
Expand All @@ -65,6 +65,7 @@ public boolean init(Literal<?>[] args, int matchedPattern, ParseResult parseResu
data.priority = EventPriority.valueOf(lastTag.toUpperCase(Locale.ENGLISH));
}

assert entryContainer != null;
event = SkriptEvent.parse(expr, entryContainer.getSource(), null);

// cleanup after ourselves
Expand Down
13 changes: 10 additions & 3 deletions src/main/java/ch/njol/skript/structures/StructFunction.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import ch.njol.skript.ScriptLoader;
import ch.njol.skript.Skript;
import ch.njol.skript.config.SectionNode;
import ch.njol.skript.doc.Description;
import ch.njol.skript.doc.Examples;
import ch.njol.skript.doc.Name;
Expand Down Expand Up @@ -70,20 +71,25 @@ public class StructFunction extends Structure {
);
}

@SuppressWarnings("NotNullFieldNotInitialized")
private SectionNode source;
@Nullable
private Signature<?> signature;
private boolean local;

@Override
public boolean init(Literal<?>[] literals, int matchedPattern, ParseResult parseResult, EntryContainer entryContainer) {
public boolean init(Literal<?>[] literals, int matchedPattern, ParseResult parseResult, @Nullable EntryContainer entryContainer) {
assert entryContainer != null; // cannot be null for non-simple structures
this.source = entryContainer.getSource();
local = parseResult.hasTag("local");
return true;
}

@Override
public boolean preLoad() {
// match signature against pattern
String rawSignature = getEntryContainer().getSource().getKey();
// noinspection ConstantConditions - entry container cannot be null as this structure is not simple
String rawSignature = source.getKey();
assert rawSignature != null;
rawSignature = ScriptLoader.replaceOptions(rawSignature);
Matcher matcher = SIGNATURE_PATTERN.matcher(rawSignature);
Expand All @@ -110,7 +116,8 @@ public boolean load() {
parser.setCurrentEvent((local ? "local " : "") + "function", FunctionEvent.class);

assert signature != null;
Functions.loadFunction(parser.getCurrentScript(), getEntryContainer().getSource(), signature);
// noinspection ConstantConditions - entry container cannot be null as this structure is not simple
Functions.loadFunction(parser.getCurrentScript(), source, signature);

parser.deleteCurrentEvent();

Expand Down
3 changes: 2 additions & 1 deletion src/main/java/ch/njol/skript/structures/StructOptions.java
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@ public class StructOptions extends Structure {
}

@Override
public boolean init(Literal<?>[] args, int matchedPattern, ParseResult parseResult, EntryContainer entryContainer) {
public boolean init(Literal<?>[] args, int matchedPattern, ParseResult parseResult, @Nullable EntryContainer entryContainer) {
// noinspection ConstantConditions - entry container cannot be null as this structure is not simple
SectionNode node = entryContainer.getSource();
node.convertToEntries(-1);
loadOptions(node, "", getParser().getCurrentScript().getData(OptionsData.class, OptionsData::new).options);
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/ch/njol/skript/structures/StructVariables.java
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,8 @@ private boolean isLoaded() {
}

@Override
public boolean init(Literal<?>[] args, int matchedPattern, ParseResult parseResult, EntryContainer entryContainer) {
public boolean init(Literal<?>[] args, int matchedPattern, ParseResult parseResult, @Nullable EntryContainer entryContainer) {
// noinspection ConstantConditions - entry container cannot be null as this structure is not simple
SectionNode node = entryContainer.getSource();
node.convertToEntries(0, "=");
List<NonNullPair<String, Object>> variables;
Expand Down
Loading
Loading