| 1 | package net.minecraft.util;
|
| 2 |
|
| 3 | import com.mojang.brigadier.StringReader;
|
| 4 | import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
| 5 | import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
| 6 | import com.mojang.serialization.Codec;
|
| 7 | import com.mojang.serialization.DataResult;
|
| 8 | import java.util.Objects;
|
| 9 | import java.util.function.Function;
|
| 10 | import net.minecraft.network.chat.Component;
|
| 11 |
|
| 12 | public class CompilableString<T> {
|
| 13 | private final String source;
|
| 14 | private final T compiled;
|
| 15 |
|
| 16 | private CompilableString(final String source, final T compiled) {
|
| 17 | this.source = source;
|
| 18 | this.compiled = compiled;
|
| 19 | }
|
| 20 |
|
| 21 | public static <T> Codec<CompilableString<T>> codec(final Function<String, DataResult<T>> compiler) {
|
| 22 | return Codec.STRING.comapFlatMap(s -> compiler.apply(s).map(compiled -> new CompilableString<>(s, (T)compiled)), CompilableString::source);
|
| 23 | }
|
| 24 |
|
| 25 | public String source() {
|
| 26 | return this.source;
|
| 27 | }
|
| 28 |
|
| 29 | public T compiled() {
|
| 30 | return this.compiled;
|
| 31 | }
|
| 32 |
|
| 33 | @Override
|
| 34 | public boolean equals(final Object o) {
|
| 35 | return o instanceof CompilableString<?> that && Objects.equals(this.source, that.source);
|
| 36 | }
|
| 37 |
|
| 38 | @Override
|
| 39 | public int hashCode() {
|
| 40 | return this.source.hashCode();
|
| 41 | }
|
| 42 |
|
| 43 | @Override
|
| 44 | public String toString() {
|
| 45 | return this.source;
|
| 46 | }
|
| 47 |
|
| 48 | public abstract static class CommandParserHelper<T> implements Function<String, DataResult<T>> {
|
| 49 | private static final DynamicCommandExceptionType TRAILING_DATA = new DynamicCommandExceptionType(
|
| 50 | commandAndRemainder -> Component.translatableEscape("command.trailing_data", commandAndRemainder)
|
| 51 | );
|
| 52 |
|
| 53 | public final DataResult<T> apply(final String contents) {
|
| 54 | StringReader reader = new StringReader(contents);
|
| 55 |
|
| 56 | try {
|
| 57 | T result = this.parse(reader);
|
| 58 | if (reader.canRead()) {
|
| 59 | String parsed = reader.getString().substring(0, reader.getCursor());
|
| 60 | String leftovers = reader.getString().substring(reader.getCursor());
|
| 61 | throw TRAILING_DATA.create(parsed + "[" + leftovers + "]");
|
| 62 | } else {
|
| 63 | return DataResult.success(result);
|
| 64 | }
|
| 65 | } catch (CommandSyntaxException ex) {
|
| 66 | return DataResult.error(() -> this.errorMessage(contents, ex));
|
| 67 | }
|
| 68 | }
|
| 69 |
|
| 70 | protected abstract T parse(StringReader reader) throws CommandSyntaxException;
|
| 71 |
|
| 72 | protected abstract String errorMessage(String original, CommandSyntaxException exception);
|
| 73 | }
|
| 74 | }
|
| 75 |
|