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

Meta-syntax and annotations. #6571

Draft
wants to merge 11 commits into
base: dev/feature
Choose a base branch
from
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
19 changes: 15 additions & 4 deletions src/main/java/ch/njol/skript/Skript.java
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,6 @@
import ch.njol.util.Kleenean;
import ch.njol.util.NullableChecker;
import ch.njol.util.StringUtils;
import ch.njol.util.coll.CollectionUtils;
import ch.njol.util.coll.iterator.CheckedIterator;
import ch.njol.util.coll.iterator.EnumerationIterable;
import com.google.common.collect.Lists;
Expand Down Expand Up @@ -116,6 +115,7 @@
import org.skriptlang.skript.lang.converter.Converter;
import org.skriptlang.skript.lang.converter.Converters;
import org.skriptlang.skript.lang.entry.EntryValidator;
import org.skriptlang.skript.lang.script.Annotation;
import org.skriptlang.skript.lang.script.Script;
import org.skriptlang.skript.lang.structure.Structure;
import org.skriptlang.skript.lang.structure.StructureInfo;
Expand Down 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 Expand Up @@ -1605,16 +1612,18 @@ public static void info(final String info) {
*/
@SuppressWarnings("null")
public static void warning(final String warning) {
SkriptLogger.log(Level.WARNING, warning);
if (!Annotation.isAnnotationPresent("suppress warnings"))
SkriptLogger.log(Level.WARNING, warning);
}

/**
* @see SkriptLogger#log(Level, String)
*/
@SuppressWarnings("null")
public static void error(final @Nullable String error) {
if (error != null)
SkriptLogger.log(Level.SEVERE, error);
if (error == null || Annotation.isAnnotationPresent("suppress errors"))
return;
SkriptLogger.log(Level.SEVERE, error);
}

/**
Expand All @@ -1625,6 +1634,8 @@ public static void error(final @Nullable String error) {
* @param quality
*/
public static void error(final String error, final ErrorQuality quality) {
if (Annotation.isAnnotationPresent("suppress errors"))
return;
SkriptLogger.log(new LogEntry(SkriptLogger.SEVERE, quality, error));
}

Expand Down
83 changes: 83 additions & 0 deletions src/main/java/ch/njol/skript/effects/EffAnnotate.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/**
* This file is part of Skript.
*
* 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.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with Skript. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright Peter Güttinger, SkriptLang team and contributors
*/
package ch.njol.skript.effects;

import ch.njol.skript.Skript;
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.Effect;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.MetaSyntaxElement;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.util.Kleenean;
import org.bukkit.event.Event;
import org.eclipse.jdt.annotation.Nullable;
import org.jetbrains.annotations.UnknownNullability;
import org.skriptlang.skript.lang.script.Annotation;

/**
* @author moderocky
*/
@Name("Annotation (Code)")
@Description({
"A special metadata note visible to the next real line of code.",
"This does nothing by itself, but may change the behaviour of the following line.",
"If the annotation does not exist (or the following line does not use it) then it will have no effect.",
"There is no penalty for using annotations that do not exist."
})
@Examples({
"on join:",
"\t@suppress warnings",
"\t@suppress errors",
"\tbroadcast \"hello there!\""
})
@Since("INSERT VERSION")
public class EffAnnotate extends Effect implements MetaSyntaxElement {

static {
Skript.registerEffect(EffAnnotate.class, "@<.+>");
}

private @UnknownNullability Annotation annotation;

@Override
public boolean init(Expression<?>[] expressions, int pattern, Kleenean delayed, ParseResult result) {
String text = result.regexes.get(0).group().trim();
if (text.isEmpty()) {
Skript.error("You must specify a text to annotate.");
return false;
}
this.annotation = Annotation.create(text);
this.getParser().addAnnotation(annotation);
Skript.debug("found annotation: " + annotation);
return true;
}

@Override
protected void execute(Event event) {
}

@Override
public String toString(@Nullable Event event, boolean debug) {
return '@' + annotation.value();
}

}
32 changes: 32 additions & 0 deletions src/main/java/ch/njol/skript/lang/MetaSyntaxElement.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* This file is part of Skript.
*
* 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.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with Skript. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright Peter Güttinger, SkriptLang team and contributors
*/
package ch.njol.skript.lang;

/**
* Represents a type of syntax element used to modify other syntax elements rather than to provide any function
* itself.
*/
public interface MetaSyntaxElement extends SyntaxElement {

@Override
default boolean consumeAnnotations() {
return false;
}

}