| 1 | package net.minecraft.commands.functions;
|
| 2 |
|
| 3 | import it.unimi.dsi.fastutil.ints.IntArrayList;
|
| 4 | import it.unimi.dsi.fastutil.ints.IntList;
|
| 5 | import java.util.ArrayList;
|
| 6 | import java.util.List;
|
| 7 | import net.minecraft.commands.ExecutionCommandSource;
|
| 8 | import net.minecraft.commands.execution.UnboundEntryAction;
|
| 9 | import net.minecraft.resources.Identifier;
|
| 10 | import org.jspecify.annotations.Nullable;
|
| 11 |
|
| 12 | class FunctionBuilder<T extends ExecutionCommandSource<T>> {
|
| 13 | private @Nullable List<UnboundEntryAction<T>> plainEntries = new ArrayList<>();
|
| 14 | private @Nullable List<MacroFunction.Entry<T>> macroEntries;
|
| 15 | private final List<String> macroArguments = new ArrayList<>();
|
| 16 |
|
| 17 | public void addCommand(final UnboundEntryAction<T> command) {
|
| 18 | if (this.macroEntries != null) {
|
| 19 | this.macroEntries.add(new MacroFunction.PlainTextEntry<>(command));
|
| 20 | } else {
|
| 21 | this.plainEntries.add(command);
|
| 22 | }
|
| 23 | }
|
| 24 |
|
| 25 | private int getArgumentIndex(final String id) {
|
| 26 | int index = this.macroArguments.indexOf(id);
|
| 27 | if (index == -1) {
|
| 28 | index = this.macroArguments.size();
|
| 29 | this.macroArguments.add(id);
|
| 30 | }
|
| 31 |
|
| 32 | return index;
|
| 33 | }
|
| 34 |
|
| 35 | private IntList convertToIndices(final List<String> ids) {
|
| 36 | IntArrayList result = new IntArrayList(ids.size());
|
| 37 |
|
| 38 | for (String id : ids) {
|
| 39 | result.add(this.getArgumentIndex(id));
|
| 40 | }
|
| 41 |
|
| 42 | return result;
|
| 43 | }
|
| 44 |
|
| 45 | public void addMacro(final String command, final int line, final T compilationContext) {
|
| 46 | StringTemplate parseResults;
|
| 47 | try {
|
| 48 | parseResults = StringTemplate.fromString(command);
|
| 49 | } catch (Exception e) {
|
| 50 | throw new IllegalArgumentException("Can't parse function line " + line + ": '" + command + "'", e);
|
| 51 | }
|
| 52 |
|
| 53 | if (this.plainEntries != null) {
|
| 54 | this.macroEntries = new ArrayList<>(this.plainEntries.size() + 1);
|
| 55 |
|
| 56 | for (UnboundEntryAction<T> plainEntry : this.plainEntries) {
|
| 57 | this.macroEntries.add(new MacroFunction.PlainTextEntry<>(plainEntry));
|
| 58 | }
|
| 59 |
|
| 60 | this.plainEntries = null;
|
| 61 | }
|
| 62 |
|
| 63 | this.macroEntries.add(new MacroFunction.MacroEntry<>(parseResults, this.convertToIndices(parseResults.variables()), compilationContext));
|
| 64 | }
|
| 65 |
|
| 66 | public CommandFunction<T> build(final Identifier id) {
|
| 67 | return this.macroEntries != null ? new MacroFunction<>(id, this.macroEntries, this.macroArguments) : new PlainTextFunction<>(id, this.plainEntries);
|
| 68 | }
|
| 69 | }
|
| 70 |
|