| 1 | package net.minecraft.nbt;
|
| 2 |
|
| 3 | import com.google.common.collect.ImmutableMap;
|
| 4 | import com.google.common.collect.ImmutableMap.Builder;
|
| 5 | import com.google.common.primitives.UnsignedBytes;
|
| 6 | import com.mojang.brigadier.StringReader;
|
| 7 | import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
| 8 | import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
| 9 | import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
| 10 | import com.mojang.serialization.DynamicOps;
|
| 11 | import com.mojang.serialization.JavaOps;
|
| 12 | import it.unimi.dsi.fastutil.bytes.ByteArrayList;
|
| 13 | import it.unimi.dsi.fastutil.bytes.ByteList;
|
| 14 | import it.unimi.dsi.fastutil.chars.CharList;
|
| 15 | import java.nio.ByteBuffer;
|
| 16 | import java.util.HexFormat;
|
| 17 | import java.util.List;
|
| 18 | import java.util.Locale;
|
| 19 | import java.util.Map;
|
| 20 | import java.util.Objects;
|
| 21 | import java.util.Set;
|
| 22 | import java.util.Map.Entry;
|
| 23 | import java.util.regex.Pattern;
|
| 24 | import java.util.stream.IntStream;
|
| 25 | import java.util.stream.LongStream;
|
| 26 | import net.minecraft.network.chat.Component;
|
| 27 | import net.minecraft.util.parsing.packrat.Atom;
|
| 28 | import net.minecraft.util.parsing.packrat.DelayedException;
|
| 29 | import net.minecraft.util.parsing.packrat.Dictionary;
|
| 30 | import net.minecraft.util.parsing.packrat.NamedRule;
|
| 31 | import net.minecraft.util.parsing.packrat.ParseState;
|
| 32 | import net.minecraft.util.parsing.packrat.Scope;
|
| 33 | import net.minecraft.util.parsing.packrat.Term;
|
| 34 | import net.minecraft.util.parsing.packrat.commands.Grammar;
|
| 35 | import net.minecraft.util.parsing.packrat.commands.GreedyPatternParseRule;
|
| 36 | import net.minecraft.util.parsing.packrat.commands.GreedyPredicateParseRule;
|
| 37 | import net.minecraft.util.parsing.packrat.commands.NumberRunParseRule;
|
| 38 | import net.minecraft.util.parsing.packrat.commands.StringReaderTerms;
|
| 39 | import net.minecraft.util.parsing.packrat.commands.UnquotedStringParseRule;
|
| 40 | import org.jspecify.annotations.Nullable;
|
| 41 |
|
| 42 | public class SnbtGrammar {
|
| 43 | private static final DynamicCommandExceptionType ERROR_NUMBER_PARSE_FAILURE = new DynamicCommandExceptionType(
|
| 44 | message -> Component.translatableEscape("snbt.parser.number_parse_failure", message)
|
| 45 | );
|
| 46 | private static final DynamicCommandExceptionType ERROR_EXPECTED_HEX_ESCAPE = new DynamicCommandExceptionType(
|
| 47 | length -> Component.translatableEscape("snbt.parser.expected_hex_escape", length)
|
| 48 | );
|
| 49 | private static final DynamicCommandExceptionType ERROR_INVALID_CODEPOINT = new DynamicCommandExceptionType(
|
| 50 | codepoint -> Component.translatableEscape("snbt.parser.invalid_codepoint", codepoint)
|
| 51 | );
|
| 52 | private static final DynamicCommandExceptionType ERROR_NO_SUCH_OPERATION = new DynamicCommandExceptionType(
|
| 53 | operation -> Component.translatableEscape("snbt.parser.no_such_operation", operation)
|
| 54 | );
|
| 55 | private static final DelayedException<CommandSyntaxException> ERROR_EXPECTED_INTEGER_TYPE = DelayedException.create(
|
| 56 | new SimpleCommandExceptionType(Component.translatable("snbt.parser.expected_integer_type"))
|
| 57 | );
|
| 58 | private static final DelayedException<CommandSyntaxException> ERROR_EXPECTED_FLOAT_TYPE = DelayedException.create(
|
| 59 | new SimpleCommandExceptionType(Component.translatable("snbt.parser.expected_float_type"))
|
| 60 | );
|
| 61 | private static final DelayedException<CommandSyntaxException> ERROR_EXPECTED_NON_NEGATIVE_NUMBER = DelayedException.create(
|
| 62 | new SimpleCommandExceptionType(Component.translatable("snbt.parser.expected_non_negative_number"))
|
| 63 | );
|
| 64 | private static final DelayedException<CommandSyntaxException> ERROR_INVALID_CHARACTER_NAME = DelayedException.create(
|
| 65 | new SimpleCommandExceptionType(Component.translatable("snbt.parser.invalid_character_name"))
|
| 66 | );
|
| 67 | private static final DelayedException<CommandSyntaxException> ERROR_INVALID_ARRAY_ELEMENT_TYPE = DelayedException.create(
|
| 68 | new SimpleCommandExceptionType(Component.translatable("snbt.parser.invalid_array_element_type"))
|
| 69 | );
|
| 70 | private static final DelayedException<CommandSyntaxException> ERROR_INVALID_UNQUOTED_START = DelayedException.create(
|
| 71 | new SimpleCommandExceptionType(Component.translatable("snbt.parser.invalid_unquoted_start"))
|
| 72 | );
|
| 73 | private static final DelayedException<CommandSyntaxException> ERROR_EXPECTED_UNQUOTED_STRING = DelayedException.create(
|
| 74 | new SimpleCommandExceptionType(Component.translatable("snbt.parser.expected_unquoted_string"))
|
| 75 | );
|
| 76 | private static final DelayedException<CommandSyntaxException> ERROR_INVALID_STRING_CONTENTS = DelayedException.create(
|
| 77 | new SimpleCommandExceptionType(Component.translatable("snbt.parser.invalid_string_contents"))
|
| 78 | );
|
| 79 | private static final DelayedException<CommandSyntaxException> ERROR_EXPECTED_BINARY_NUMERAL = DelayedException.create(
|
| 80 | new SimpleCommandExceptionType(Component.translatable("snbt.parser.expected_binary_numeral"))
|
| 81 | );
|
| 82 | private static final DelayedException<CommandSyntaxException> ERROR_UNDESCORE_NOT_ALLOWED = DelayedException.create(
|
| 83 | new SimpleCommandExceptionType(Component.translatable("snbt.parser.underscore_not_allowed"))
|
| 84 | );
|
| 85 | private static final DelayedException<CommandSyntaxException> ERROR_EXPECTED_DECIMAL_NUMERAL = DelayedException.create(
|
| 86 | new SimpleCommandExceptionType(Component.translatable("snbt.parser.expected_decimal_numeral"))
|
| 87 | );
|
| 88 | private static final DelayedException<CommandSyntaxException> ERROR_EXPECTED_HEX_NUMERAL = DelayedException.create(
|
| 89 | new SimpleCommandExceptionType(Component.translatable("snbt.parser.expected_hex_numeral"))
|
| 90 | );
|
| 91 | private static final DelayedException<CommandSyntaxException> ERROR_EMPTY_KEY = DelayedException.create(
|
| 92 | new SimpleCommandExceptionType(Component.translatable("snbt.parser.empty_key"))
|
| 93 | );
|
| 94 | private static final DelayedException<CommandSyntaxException> ERROR_LEADING_ZERO_NOT_ALLOWED = DelayedException.create(
|
| 95 | new SimpleCommandExceptionType(Component.translatable("snbt.parser.leading_zero_not_allowed"))
|
| 96 | );
|
| 97 | private static final DelayedException<CommandSyntaxException> ERROR_INFINITY_NOT_ALLOWED = DelayedException.create(
|
| 98 | new SimpleCommandExceptionType(Component.translatable("snbt.parser.infinity_not_allowed"))
|
| 99 | );
|
| 100 | private static final HexFormat HEX_ESCAPE = HexFormat.of().withUpperCase();
|
| 101 | private static final NumberRunParseRule BINARY_NUMERAL = new NumberRunParseRule(ERROR_EXPECTED_BINARY_NUMERAL, ERROR_UNDESCORE_NOT_ALLOWED) {
|
| 102 | @Override
|
| 103 | protected boolean isAccepted(final char c) {
|
| 104 | return switch (c) {
|
| 105 | case '0', '1', '_' -> true;
|
| 106 | default -> false;
|
| 107 | };
|
| 108 | }
|
| 109 | };
|
| 110 | private static final NumberRunParseRule DECIMAL_NUMERAL = new NumberRunParseRule(ERROR_EXPECTED_DECIMAL_NUMERAL, ERROR_UNDESCORE_NOT_ALLOWED) {
|
| 111 | @Override
|
| 112 | protected boolean isAccepted(final char c) {
|
| 113 | return switch (c) {
|
| 114 | case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '_' -> true;
|
| 115 | default -> false;
|
| 116 | };
|
| 117 | }
|
| 118 | };
|
| 119 | private static final NumberRunParseRule HEX_NUMERAL = new NumberRunParseRule(ERROR_EXPECTED_HEX_NUMERAL, ERROR_UNDESCORE_NOT_ALLOWED) {
|
| 120 | @Override
|
| 121 | protected boolean isAccepted(final char c) {
|
| 122 | return switch (c) {
|
| 123 | case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', '_', 'a', 'b', 'c', 'd', 'e', 'f' -> true;
|
| 124 | default -> false;
|
| 125 | };
|
| 126 | }
|
| 127 | };
|
| 128 | private static final GreedyPredicateParseRule PLAIN_STRING_CHUNK = new GreedyPredicateParseRule(1, ERROR_INVALID_STRING_CONTENTS) {
|
| 129 | @Override
|
| 130 | protected boolean isAccepted(final char c) {
|
| 131 | return switch (c) {
|
| 132 | case '"', '\'', '\\' -> false;
|
| 133 | default -> true;
|
| 134 | };
|
| 135 | }
|
| 136 | };
|
| 137 | private static final StringReaderTerms.TerminalCharacters NUMBER_LOOKEAHEAD = new StringReaderTerms.TerminalCharacters(CharList.of()) {
|
| 138 | @Override
|
| 139 | protected boolean isAccepted(final char c) {
|
| 140 | return SnbtGrammar.canStartNumber(c);
|
| 141 | }
|
| 142 | };
|
| 143 | private static final Pattern UNICODE_NAME = Pattern.compile("[-a-zA-Z0-9 ]+");
|
| 144 |
|
| 145 | private static DelayedException<CommandSyntaxException> createNumberParseError(final NumberFormatException ex) {
|
| 146 | return DelayedException.create(ERROR_NUMBER_PARSE_FAILURE, ex.getMessage());
|
| 147 | }
|
| 148 |
|
| 149 | public static @Nullable String escapeControlCharacters(final char c) {
|
| 150 | return switch (c) {
|
| 151 | case '\b' -> "b";
|
| 152 | case '\t' -> "t";
|
| 153 | case '\n' -> "n";
|
| 154 | default -> c < ' ' ? "x" + HEX_ESCAPE.toHexDigits((byte)c) : null;
|
| 155 | case '\f' -> "f";
|
| 156 | case '\r' -> "r";
|
| 157 | };
|
| 158 | }
|
| 159 |
|
| 160 | private static boolean isAllowedToStartUnquotedString(final char c) {
|
| 161 | return !canStartNumber(c);
|
| 162 | }
|
| 163 |
|
| 164 | private static boolean canStartNumber(final char c) {
|
| 165 | return switch (c) {
|
| 166 | case '+', '-', '.', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' -> true;
|
| 167 | default -> false;
|
| 168 | };
|
| 169 | }
|
| 170 |
|
| 171 | private static boolean needsUnderscoreRemoval(final String contents) {
|
| 172 | return contents.indexOf(95) != -1;
|
| 173 | }
|
| 174 |
|
| 175 | private static void cleanAndAppend(final StringBuilder output, final String contents) {
|
| 176 | cleanAndAppend(output, contents, needsUnderscoreRemoval(contents));
|
| 177 | }
|
| 178 |
|
| 179 | private static void cleanAndAppend(final StringBuilder output, final String contents, final boolean needsUnderscoreRemoval) {
|
| 180 | if (needsUnderscoreRemoval) {
|
| 181 | for (char c : contents.toCharArray()) {
|
| 182 | if (c != '_') {
|
| 183 | output.append(c);
|
| 184 | }
|
| 185 | }
|
| 186 | } else {
|
| 187 | output.append(contents);
|
| 188 | }
|
| 189 | }
|
| 190 |
|
| 191 | private static short parseUnsignedShort(final String string, final int radix) {
|
| 192 | int parse = Integer.parseInt(string, radix);
|
| 193 | if (parse >> 16 == 0) {
|
| 194 | return (short)parse;
|
| 195 | } else {
|
| 196 | throw new NumberFormatException("out of range: " + parse);
|
| 197 | }
|
| 198 | }
|
| 199 |
|
| 200 | private static <T> @Nullable T createFloat(
|
| 201 | final DynamicOps<T> ops,
|
| 202 | final SnbtGrammar.Sign sign,
|
| 203 | final @Nullable String whole,
|
| 204 | final @Nullable String fraction,
|
| 205 | final SnbtGrammar.@Nullable Signed<String> exponent,
|
| 206 | final SnbtGrammar.@Nullable TypeSuffix typeSuffix,
|
| 207 | final ParseState<?> state
|
| 208 | ) {
|
| 209 | StringBuilder result = new StringBuilder();
|
| 210 | sign.append(result);
|
| 211 | if (whole != null) {
|
| 212 | cleanAndAppend(result, whole);
|
| 213 | }
|
| 214 |
|
| 215 | if (fraction != null) {
|
| 216 | result.append('.');
|
| 217 | cleanAndAppend(result, fraction);
|
| 218 | }
|
| 219 |
|
| 220 | if (exponent != null) {
|
| 221 | result.append('e');
|
| 222 | exponent.sign().append(result);
|
| 223 | cleanAndAppend(result, exponent.value);
|
| 224 | }
|
| 225 |
|
| 226 | try {
|
| 227 | String contents = result.toString();
|
| 228 |
|
| 229 | return (T)(switch (typeSuffix) {
|
| 230 | case null -> convertDouble(ops, state, contents);
|
| 231 | case FLOAT -> convertFloat(ops, state, contents);
|
| 232 | case DOUBLE -> convertDouble(ops, state, contents);
|
| 233 | default -> {
|
| 234 | state.errorCollector().store(state.mark(), ERROR_EXPECTED_FLOAT_TYPE);
|
| 235 | yield null;
|
| 236 | }
|
| 237 | });
|
| 238 | } catch (NumberFormatException e) {
|
| 239 | state.errorCollector().store(state.mark(), createNumberParseError(e));
|
| 240 | return null;
|
| 241 | }
|
| 242 | }
|
| 243 |
|
| 244 | private static <T> @Nullable T convertFloat(final DynamicOps<T> ops, final ParseState<?> state, final String contents) {
|
| 245 | float value = Float.parseFloat(contents);
|
| 246 | if (!Float.isFinite(value)) {
|
| 247 | state.errorCollector().store(state.mark(), ERROR_INFINITY_NOT_ALLOWED);
|
| 248 | return null;
|
| 249 | } else {
|
| 250 | return ops.createFloat(value);
|
| 251 | }
|
| 252 | }
|
| 253 |
|
| 254 | private static <T> @Nullable T convertDouble(final DynamicOps<T> ops, final ParseState<?> state, final String contents) {
|
| 255 | double value = Double.parseDouble(contents);
|
| 256 | if (!Double.isFinite(value)) {
|
| 257 | state.errorCollector().store(state.mark(), ERROR_INFINITY_NOT_ALLOWED);
|
| 258 | return null;
|
| 259 | } else {
|
| 260 | return ops.createDouble(value);
|
| 261 | }
|
| 262 | }
|
| 263 |
|
| 264 | private static String joinList(final List<String> list) {
|
| 265 | return switch (list.size()) {
|
| 266 | case 0 -> "";
|
| 267 | case 1 -> (String)list.getFirst();
|
| 268 | default -> String.join("", list);
|
| 269 | };
|
| 270 | }
|
| 271 |
|
| 272 | public static <T> Grammar<T> createParser(final DynamicOps<T> ops) {
|
| 273 | T trueValue = ops.createBoolean(true);
|
| 274 | T falseValue = ops.createBoolean(false);
|
| 275 | T emptyMapValue = ops.emptyMap();
|
| 276 | T emptyList = ops.emptyList();
|
| 277 | Dictionary<StringReader> rules = new Dictionary<>();
|
| 278 | Atom<SnbtGrammar.Sign> sign = Atom.of("sign");
|
| 279 | rules.put(
|
| 280 | sign,
|
| 281 | Term.alternative(
|
| 282 | Term.sequence(StringReaderTerms.character('+'), Term.marker(sign, SnbtGrammar.Sign.PLUS)),
|
| 283 | Term.sequence(StringReaderTerms.character('-'), Term.marker(sign, SnbtGrammar.Sign.MINUS))
|
| 284 | ),
|
| 285 | scope -> scope.getOrThrow(sign)
|
| 286 | );
|
| 287 | Atom<SnbtGrammar.IntegerSuffix> integerSuffix = Atom.of("integer_suffix");
|
| 288 | rules.put(
|
| 289 | integerSuffix,
|
| 290 | Term.alternative(
|
| 291 | Term.sequence(
|
| 292 | StringReaderTerms.characters('u', 'U'),
|
| 293 | Term.alternative(
|
| 294 | Term.sequence(
|
| 295 | StringReaderTerms.characters('b', 'B'),
|
| 296 | Term.marker(integerSuffix, new SnbtGrammar.IntegerSuffix(SnbtGrammar.SignedPrefix.UNSIGNED, SnbtGrammar.TypeSuffix.BYTE))
|
| 297 | ),
|
| 298 | Term.sequence(
|
| 299 | StringReaderTerms.characters('s', 'S'),
|
| 300 | Term.marker(integerSuffix, new SnbtGrammar.IntegerSuffix(SnbtGrammar.SignedPrefix.UNSIGNED, SnbtGrammar.TypeSuffix.SHORT))
|
| 301 | ),
|
| 302 | Term.sequence(
|
| 303 | StringReaderTerms.characters('i', 'I'),
|
| 304 | Term.marker(integerSuffix, new SnbtGrammar.IntegerSuffix(SnbtGrammar.SignedPrefix.UNSIGNED, SnbtGrammar.TypeSuffix.INT))
|
| 305 | ),
|
| 306 | Term.sequence(
|
| 307 | StringReaderTerms.characters('l', 'L'),
|
| 308 | Term.marker(integerSuffix, new SnbtGrammar.IntegerSuffix(SnbtGrammar.SignedPrefix.UNSIGNED, SnbtGrammar.TypeSuffix.LONG))
|
| 309 | )
|
| 310 | )
|
| 311 | ),
|
| 312 | Term.sequence(
|
| 313 | StringReaderTerms.characters('s', 'S'),
|
| 314 | Term.alternative(
|
| 315 | Term.sequence(
|
| 316 | StringReaderTerms.characters('b', 'B'),
|
| 317 | Term.marker(integerSuffix, new SnbtGrammar.IntegerSuffix(SnbtGrammar.SignedPrefix.SIGNED, SnbtGrammar.TypeSuffix.BYTE))
|
| 318 | ),
|
| 319 | Term.sequence(
|
| 320 | StringReaderTerms.characters('s', 'S'),
|
| 321 | Term.marker(integerSuffix, new SnbtGrammar.IntegerSuffix(SnbtGrammar.SignedPrefix.SIGNED, SnbtGrammar.TypeSuffix.SHORT))
|
| 322 | ),
|
| 323 | Term.sequence(
|
| 324 | StringReaderTerms.characters('i', 'I'),
|
| 325 | Term.marker(integerSuffix, new SnbtGrammar.IntegerSuffix(SnbtGrammar.SignedPrefix.SIGNED, SnbtGrammar.TypeSuffix.INT))
|
| 326 | ),
|
| 327 | Term.sequence(
|
| 328 | StringReaderTerms.characters('l', 'L'),
|
| 329 | Term.marker(integerSuffix, new SnbtGrammar.IntegerSuffix(SnbtGrammar.SignedPrefix.SIGNED, SnbtGrammar.TypeSuffix.LONG))
|
| 330 | )
|
| 331 | )
|
| 332 | ),
|
| 333 | Term.sequence(StringReaderTerms.characters('b', 'B'), Term.marker(integerSuffix, new SnbtGrammar.IntegerSuffix(null, SnbtGrammar.TypeSuffix.BYTE))),
|
| 334 | Term.sequence(StringReaderTerms.characters('s', 'S'), Term.marker(integerSuffix, new SnbtGrammar.IntegerSuffix(null, SnbtGrammar.TypeSuffix.SHORT))),
|
| 335 | Term.sequence(StringReaderTerms.characters('i', 'I'), Term.marker(integerSuffix, new SnbtGrammar.IntegerSuffix(null, SnbtGrammar.TypeSuffix.INT))),
|
| 336 | Term.sequence(StringReaderTerms.characters('l', 'L'), Term.marker(integerSuffix, new SnbtGrammar.IntegerSuffix(null, SnbtGrammar.TypeSuffix.LONG)))
|
| 337 | ),
|
| 338 | scope -> scope.getOrThrow(integerSuffix)
|
| 339 | );
|
| 340 | Atom<String> binaryNumeral = Atom.of("binary_numeral");
|
| 341 | rules.put(binaryNumeral, BINARY_NUMERAL);
|
| 342 | Atom<String> decimalNumeral = Atom.of("decimal_numeral");
|
| 343 | rules.put(decimalNumeral, DECIMAL_NUMERAL);
|
| 344 | Atom<String> hexNumeral = Atom.of("hex_numeral");
|
| 345 | rules.put(hexNumeral, HEX_NUMERAL);
|
| 346 | Atom<SnbtGrammar.IntegerLiteral> integerLiteral = Atom.of("integer_literal");
|
| 347 | NamedRule<StringReader, SnbtGrammar.IntegerLiteral> integerLiteralRule = rules.put(
|
| 348 | integerLiteral,
|
| 349 | Term.sequence(
|
| 350 | Term.optional(rules.named(sign)),
|
| 351 | Term.alternative(
|
| 352 | Term.sequence(
|
| 353 | StringReaderTerms.character('0'),
|
| 354 | Term.cut(),
|
| 355 | Term.alternative(
|
| 356 | Term.sequence(StringReaderTerms.characters('x', 'X'), Term.cut(), rules.named(hexNumeral)),
|
| 357 | Term.sequence(StringReaderTerms.characters('b', 'B'), rules.named(binaryNumeral)),
|
| 358 | Term.sequence(rules.named(decimalNumeral), Term.cut(), Term.fail(ERROR_LEADING_ZERO_NOT_ALLOWED)),
|
| 359 | Term.marker(decimalNumeral, "0")
|
| 360 | )
|
| 361 | ),
|
| 362 | rules.named(decimalNumeral)
|
| 363 | ),
|
| 364 | Term.optional(rules.named(integerSuffix))
|
| 365 | ),
|
| 366 | scope -> {
|
| 367 | SnbtGrammar.IntegerSuffix suffix = scope.getOrDefault(integerSuffix, SnbtGrammar.IntegerSuffix.EMPTY);
|
| 368 | SnbtGrammar.Sign signValue = scope.getOrDefault(sign, SnbtGrammar.Sign.PLUS);
|
| 369 | String decimalContents = scope.get(decimalNumeral);
|
| 370 | if (decimalContents != null) {
|
| 371 | return new SnbtGrammar.IntegerLiteral(signValue, SnbtGrammar.Base.DECIMAL, decimalContents, suffix);
|
| 372 | }
|
| 373 |
|
| 374 | String hexContents = scope.get(hexNumeral);
|
| 375 | if (hexContents != null) {
|
| 376 | return new SnbtGrammar.IntegerLiteral(signValue, SnbtGrammar.Base.HEX, hexContents, suffix);
|
| 377 | }
|
| 378 |
|
| 379 | String binaryContents = scope.getOrThrow(binaryNumeral);
|
| 380 | return new SnbtGrammar.IntegerLiteral(signValue, SnbtGrammar.Base.BINARY, binaryContents, suffix);
|
| 381 | }
|
| 382 | );
|
| 383 | Atom<SnbtGrammar.TypeSuffix> floatTypeSuffix = Atom.of("float_type_suffix");
|
| 384 | rules.put(
|
| 385 | floatTypeSuffix,
|
| 386 | Term.alternative(
|
| 387 | Term.sequence(StringReaderTerms.characters('f', 'F'), Term.marker(floatTypeSuffix, SnbtGrammar.TypeSuffix.FLOAT)),
|
| 388 | Term.sequence(StringReaderTerms.characters('d', 'D'), Term.marker(floatTypeSuffix, SnbtGrammar.TypeSuffix.DOUBLE))
|
| 389 | ),
|
| 390 | scope -> scope.getOrThrow(floatTypeSuffix)
|
| 391 | );
|
| 392 | Atom<SnbtGrammar.Signed<String>> floatExponentPart = Atom.of("float_exponent_part");
|
| 393 | rules.put(
|
| 394 | floatExponentPart,
|
| 395 | Term.sequence(StringReaderTerms.characters('e', 'E'), Term.optional(rules.named(sign)), rules.named(decimalNumeral)),
|
| 396 | scope -> new SnbtGrammar.Signed<>(scope.getOrDefault(sign, SnbtGrammar.Sign.PLUS), scope.getOrThrow(decimalNumeral))
|
| 397 | );
|
| 398 | Atom<String> floatWholePart = Atom.of("float_whole_part");
|
| 399 | Atom<String> floatFractionPart = Atom.of("float_fraction_part");
|
| 400 | Atom<T> floatLiteral = Atom.of("float_literal");
|
| 401 | rules.putComplex(
|
| 402 | floatLiteral,
|
| 403 | Term.sequence(
|
| 404 | Term.optional(rules.named(sign)),
|
| 405 | Term.alternative(
|
| 406 | Term.sequence(
|
| 407 | rules.namedWithAlias(decimalNumeral, floatWholePart),
|
| 408 | StringReaderTerms.character('.'),
|
| 409 | Term.cut(),
|
| 410 | Term.optional(rules.namedWithAlias(decimalNumeral, floatFractionPart)),
|
| 411 | Term.optional(rules.named(floatExponentPart)),
|
| 412 | Term.optional(rules.named(floatTypeSuffix))
|
| 413 | ),
|
| 414 | Term.sequence(
|
| 415 | StringReaderTerms.character('.'),
|
| 416 | Term.cut(),
|
| 417 | rules.namedWithAlias(decimalNumeral, floatFractionPart),
|
| 418 | Term.optional(rules.named(floatExponentPart)),
|
| 419 | Term.optional(rules.named(floatTypeSuffix))
|
| 420 | ),
|
| 421 | Term.sequence(
|
| 422 | rules.namedWithAlias(decimalNumeral, floatWholePart), rules.named(floatExponentPart), Term.cut(), Term.optional(rules.named(floatTypeSuffix))
|
| 423 | ),
|
| 424 | Term.sequence(rules.namedWithAlias(decimalNumeral, floatWholePart), Term.optional(rules.named(floatExponentPart)), rules.named(floatTypeSuffix))
|
| 425 | )
|
| 426 | ),
|
| 427 | state -> {
|
| 428 | Scope scope = state.scope();
|
| 429 | SnbtGrammar.Sign wholeSign = scope.getOrDefault(sign, SnbtGrammar.Sign.PLUS);
|
| 430 | String whole = scope.get(floatWholePart);
|
| 431 | String fraction = scope.get(floatFractionPart);
|
| 432 | SnbtGrammar.Signed<String> exponent = scope.get(floatExponentPart);
|
| 433 | SnbtGrammar.TypeSuffix typeSuffix = scope.get(floatTypeSuffix);
|
| 434 | return createFloat(ops, wholeSign, whole, fraction, exponent, typeSuffix, state);
|
| 435 | }
|
| 436 | );
|
| 437 | Atom<String> stringHex2 = Atom.of("string_hex_2");
|
| 438 | rules.put(stringHex2, new SnbtGrammar.SimpleHexLiteralParseRule(2));
|
| 439 | Atom<String> stringHex4 = Atom.of("string_hex_4");
|
| 440 | rules.put(stringHex4, new SnbtGrammar.SimpleHexLiteralParseRule(4));
|
| 441 | Atom<String> stringHex8 = Atom.of("string_hex_8");
|
| 442 | rules.put(stringHex8, new SnbtGrammar.SimpleHexLiteralParseRule(8));
|
| 443 | Atom<String> stringUnicodeName = Atom.of("string_unicode_name");
|
| 444 | rules.put(stringUnicodeName, new GreedyPatternParseRule(UNICODE_NAME, ERROR_INVALID_CHARACTER_NAME));
|
| 445 | Atom<String> stringEscapeSequence = Atom.of("string_escape_sequence");
|
| 446 | rules.putComplex(
|
| 447 | stringEscapeSequence,
|
| 448 | Term.alternative(
|
| 449 | Term.sequence(StringReaderTerms.character('b'), Term.marker(stringEscapeSequence, "\b")),
|
| 450 | Term.sequence(StringReaderTerms.character('s'), Term.marker(stringEscapeSequence, " ")),
|
| 451 | Term.sequence(StringReaderTerms.character('t'), Term.marker(stringEscapeSequence, "\t")),
|
| 452 | Term.sequence(StringReaderTerms.character('n'), Term.marker(stringEscapeSequence, "\n")),
|
| 453 | Term.sequence(StringReaderTerms.character('f'), Term.marker(stringEscapeSequence, "\f")),
|
| 454 | Term.sequence(StringReaderTerms.character('r'), Term.marker(stringEscapeSequence, "\r")),
|
| 455 | Term.sequence(StringReaderTerms.character('\\'), Term.marker(stringEscapeSequence, "\\")),
|
| 456 | Term.sequence(StringReaderTerms.character('\''), Term.marker(stringEscapeSequence, "'")),
|
| 457 | Term.sequence(StringReaderTerms.character('"'), Term.marker(stringEscapeSequence, "\"")),
|
| 458 | Term.sequence(StringReaderTerms.character('x'), rules.named(stringHex2)),
|
| 459 | Term.sequence(StringReaderTerms.character('u'), rules.named(stringHex4)),
|
| 460 | Term.sequence(StringReaderTerms.character('U'), rules.named(stringHex8)),
|
| 461 | Term.sequence(StringReaderTerms.character('N'), StringReaderTerms.character('{'), rules.named(stringUnicodeName), StringReaderTerms.character('}'))
|
| 462 | ),
|
| 463 | state -> {
|
| 464 | Scope scope = state.scope();
|
| 465 | String plainEscape = scope.getAny(stringEscapeSequence);
|
| 466 | if (plainEscape != null) {
|
| 467 | return plainEscape;
|
| 468 | }
|
| 469 |
|
| 470 | String hexEscape = scope.getAny(stringHex2, stringHex4, stringHex8);
|
| 471 | if (hexEscape != null) {
|
| 472 | int codePoint = HexFormat.fromHexDigits(hexEscape);
|
| 473 | if (!Character.isValidCodePoint(codePoint)) {
|
| 474 | state.errorCollector().store(state.mark(), DelayedException.create(ERROR_INVALID_CODEPOINT, String.format(Locale.ROOT, "U+%08X", codePoint)));
|
| 475 | return null;
|
| 476 | } else {
|
| 477 | return Character.toString(codePoint);
|
| 478 | }
|
| 479 | } else {
|
| 480 | String character = scope.getOrThrow(stringUnicodeName);
|
| 481 |
|
| 482 | int codePoint;
|
| 483 | try {
|
| 484 | codePoint = Character.codePointOf(character);
|
| 485 | } catch (IllegalArgumentException e) {
|
| 486 | state.errorCollector().store(state.mark(), ERROR_INVALID_CHARACTER_NAME);
|
| 487 | return null;
|
| 488 | }
|
| 489 |
|
| 490 | return Character.toString(codePoint);
|
| 491 | }
|
| 492 | }
|
| 493 | );
|
| 494 | Atom<String> stringPlainContents = Atom.of("string_plain_contents");
|
| 495 | rules.put(stringPlainContents, PLAIN_STRING_CHUNK);
|
| 496 | Atom<List<String>> stringChunks = Atom.of("string_chunks");
|
| 497 | Atom<String> stringContents = Atom.of("string_contents");
|
| 498 | Atom<String> singleQuotedStringChunk = Atom.of("single_quoted_string_chunk");
|
| 499 | NamedRule<StringReader, String> singleQuotedStringChunkRule = rules.put(
|
| 500 | singleQuotedStringChunk,
|
| 501 | Term.alternative(
|
| 502 | rules.namedWithAlias(stringPlainContents, stringContents),
|
| 503 | Term.sequence(StringReaderTerms.character('\\'), rules.namedWithAlias(stringEscapeSequence, stringContents)),
|
| 504 | Term.sequence(StringReaderTerms.character('"'), Term.marker(stringContents, "\""))
|
| 505 | ),
|
| 506 | scope -> scope.getOrThrow(stringContents)
|
| 507 | );
|
| 508 | Atom<String> singleQuotedStringContents = Atom.of("single_quoted_string_contents");
|
| 509 | rules.put(singleQuotedStringContents, Term.repeated(singleQuotedStringChunkRule, stringChunks), scope -> joinList(scope.getOrThrow(stringChunks)));
|
| 510 | Atom<String> doubleQuotedStringChunk = Atom.of("double_quoted_string_chunk");
|
| 511 | NamedRule<StringReader, String> doubleQuotedStringChunkRule = rules.put(
|
| 512 | doubleQuotedStringChunk,
|
| 513 | Term.alternative(
|
| 514 | rules.namedWithAlias(stringPlainContents, stringContents),
|
| 515 | Term.sequence(StringReaderTerms.character('\\'), rules.namedWithAlias(stringEscapeSequence, stringContents)),
|
| 516 | Term.sequence(StringReaderTerms.character('\''), Term.marker(stringContents, "'"))
|
| 517 | ),
|
| 518 | scope -> scope.getOrThrow(stringContents)
|
| 519 | );
|
| 520 | Atom<String> doubleQuotedStringContents = Atom.of("double_quoted_string_contents");
|
| 521 | rules.put(doubleQuotedStringContents, Term.repeated(doubleQuotedStringChunkRule, stringChunks), scope -> joinList(scope.getOrThrow(stringChunks)));
|
| 522 | Atom<String> quotedStringLiteral = Atom.of("quoted_string_literal");
|
| 523 | rules.put(
|
| 524 | quotedStringLiteral,
|
| 525 | Term.alternative(
|
| 526 | Term.sequence(
|
| 527 | StringReaderTerms.character('"'),
|
| 528 | Term.cut(),
|
| 529 | Term.optional(rules.namedWithAlias(doubleQuotedStringContents, stringContents)),
|
| 530 | StringReaderTerms.character('"')
|
| 531 | ),
|
| 532 | Term.sequence(
|
| 533 | StringReaderTerms.character('\''), Term.optional(rules.namedWithAlias(singleQuotedStringContents, stringContents)), StringReaderTerms.character('\'')
|
| 534 | )
|
| 535 | ),
|
| 536 | scope -> scope.getOrThrow(stringContents)
|
| 537 | );
|
| 538 | Atom<String> unquotedString = Atom.of("unquoted_string");
|
| 539 | rules.put(unquotedString, new UnquotedStringParseRule(1, ERROR_EXPECTED_UNQUOTED_STRING));
|
| 540 | Atom<T> literal = Atom.of("literal");
|
| 541 | Atom<List<T>> argumentList = Atom.of("arguments");
|
| 542 | rules.put(
|
| 543 | argumentList,
|
| 544 | Term.repeatedWithTrailingSeparator(rules.forward(literal), argumentList, StringReaderTerms.character(',')),
|
| 545 | scope -> scope.getOrThrow(argumentList)
|
| 546 | );
|
| 547 | Atom<T> unquotedStringOrBuiltIn = Atom.of("unquoted_string_or_builtin");
|
| 548 | rules.putComplex(
|
| 549 | unquotedStringOrBuiltIn,
|
| 550 | Term.sequence(
|
| 551 | rules.named(unquotedString), Term.optional(Term.sequence(StringReaderTerms.character('('), rules.named(argumentList), StringReaderTerms.character(')')))
|
| 552 | ),
|
| 553 | state -> {
|
| 554 | Scope scope = state.scope();
|
| 555 | String contents = scope.getOrThrow(unquotedString);
|
| 556 | if (!contents.isEmpty() && isAllowedToStartUnquotedString(contents.charAt(0))) {
|
| 557 | List<T> arguments = scope.get(argumentList);
|
| 558 | if (arguments != null) {
|
| 559 | SnbtOperations.BuiltinKey key = new SnbtOperations.BuiltinKey(contents, arguments.size());
|
| 560 | SnbtOperations.BuiltinOperation operation = SnbtOperations.BUILTIN_OPERATIONS.get(key);
|
| 561 | if (operation != null) {
|
| 562 | return operation.run(ops, arguments, state);
|
| 563 | }
|
| 564 |
|
| 565 | state.errorCollector().store(state.mark(), DelayedException.create(ERROR_NO_SUCH_OPERATION, key.toString()));
|
| 566 | return null;
|
| 567 | } else if (contents.equalsIgnoreCase("true")) {
|
| 568 | return trueValue;
|
| 569 | } else {
|
| 570 | return contents.equalsIgnoreCase("false") ? falseValue : ops.createString(contents);
|
| 571 | }
|
| 572 | } else {
|
| 573 | state.errorCollector().store(state.mark(), SnbtOperations.BUILTIN_IDS, ERROR_INVALID_UNQUOTED_START);
|
| 574 | return null;
|
| 575 | }
|
| 576 | }
|
| 577 | );
|
| 578 | Atom<String> mapKey = Atom.of("map_key");
|
| 579 | rules.put(
|
| 580 | mapKey, Term.alternative(rules.named(quotedStringLiteral), rules.named(unquotedString)), scope -> scope.getAnyOrThrow(quotedStringLiteral, unquotedString)
|
| 581 | );
|
| 582 | Atom<Entry<String, T>> mapEntry = Atom.of("map_entry");
|
| 583 | NamedRule<StringReader, Entry<String, T>> mapEntryRule = rules.putComplex(
|
| 584 | mapEntry, Term.sequence(rules.named(mapKey), StringReaderTerms.character(':'), rules.named(literal)), state -> {
|
| 585 | Scope scope = state.scope();
|
| 586 | String key = scope.getOrThrow(mapKey);
|
| 587 | if (key.isEmpty()) {
|
| 588 | state.errorCollector().store(state.mark(), ERROR_EMPTY_KEY);
|
| 589 | return null;
|
| 590 | } else {
|
| 591 | T value = scope.getOrThrow(literal);
|
| 592 | return Map.entry(key, value);
|
| 593 | }
|
| 594 | }
|
| 595 | );
|
| 596 | Atom<List<Entry<String, T>>> mapEntries = Atom.of("map_entries");
|
| 597 | rules.put(mapEntries, Term.repeatedWithTrailingSeparator(mapEntryRule, mapEntries, StringReaderTerms.character(',')), scope -> scope.getOrThrow(mapEntries));
|
| 598 | Atom<T> mapLiteral = Atom.of("map_literal");
|
| 599 | rules.put(mapLiteral, Term.sequence(StringReaderTerms.character('{'), rules.named(mapEntries), StringReaderTerms.character('}')), scope -> {
|
| 600 | List<Entry<String, T>> entries = scope.getOrThrow(mapEntries);
|
| 601 | if (entries.isEmpty()) {
|
| 602 | return emptyMapValue;
|
| 603 | }
|
| 604 |
|
| 605 | Builder<T, T> builder = ImmutableMap.builderWithExpectedSize(entries.size());
|
| 606 |
|
| 607 | for (Entry<String, T> e : entries) {
|
| 608 | builder.put(ops.createString(e.getKey()), e.getValue());
|
| 609 | }
|
| 610 |
|
| 611 | return ops.createMap(builder.buildKeepingLast());
|
| 612 | });
|
| 613 | Atom<List<T>> listEntries = Atom.of("list_entries");
|
| 614 | rules.put(
|
| 615 | listEntries,
|
| 616 | Term.repeatedWithTrailingSeparator(rules.forward(literal), listEntries, StringReaderTerms.character(',')),
|
| 617 | scope -> scope.getOrThrow(listEntries)
|
| 618 | );
|
| 619 | Atom<SnbtGrammar.ArrayPrefix> arrayPrefix = Atom.of("array_prefix");
|
| 620 | rules.put(
|
| 621 | arrayPrefix,
|
| 622 | Term.alternative(
|
| 623 | Term.sequence(StringReaderTerms.character('B'), Term.marker(arrayPrefix, SnbtGrammar.ArrayPrefix.BYTE)),
|
| 624 | Term.sequence(StringReaderTerms.character('L'), Term.marker(arrayPrefix, SnbtGrammar.ArrayPrefix.LONG)),
|
| 625 | Term.sequence(StringReaderTerms.character('I'), Term.marker(arrayPrefix, SnbtGrammar.ArrayPrefix.INT))
|
| 626 | ),
|
| 627 | scope -> scope.getOrThrow(arrayPrefix)
|
| 628 | );
|
| 629 | Atom<List<SnbtGrammar.IntegerLiteral>> intArrayEntries = Atom.of("int_array_entries");
|
| 630 | rules.put(
|
| 631 | intArrayEntries,
|
| 632 | Term.repeatedWithTrailingSeparator(integerLiteralRule, intArrayEntries, StringReaderTerms.character(',')),
|
| 633 | scope -> scope.getOrThrow(intArrayEntries)
|
| 634 | );
|
| 635 | Atom<T> listLiteral = Atom.of("list_literal");
|
| 636 | rules.putComplex(
|
| 637 | listLiteral,
|
| 638 | Term.sequence(
|
| 639 | StringReaderTerms.character('['),
|
| 640 | Term.alternative(Term.sequence(rules.named(arrayPrefix), StringReaderTerms.character(';'), rules.named(intArrayEntries)), rules.named(listEntries)),
|
| 641 | StringReaderTerms.character(']')
|
| 642 | ),
|
| 643 | state -> {
|
| 644 | Scope scope = state.scope();
|
| 645 | SnbtGrammar.ArrayPrefix arrayType = scope.get(arrayPrefix);
|
| 646 | if (arrayType != null) {
|
| 647 | List<SnbtGrammar.IntegerLiteral> entries = scope.getOrThrow(intArrayEntries);
|
| 648 | return entries.isEmpty() ? arrayType.create(ops) : arrayType.create(ops, entries, state);
|
| 649 | } else {
|
| 650 | List<T> entries = scope.getOrThrow(listEntries);
|
| 651 | return entries.isEmpty() ? emptyList : ops.createList(entries.stream());
|
| 652 | }
|
| 653 | }
|
| 654 | );
|
| 655 | NamedRule<StringReader, T> literalRule = rules.putComplex(
|
| 656 | literal,
|
| 657 | Term.alternative(
|
| 658 | Term.sequence(Term.positiveLookahead(NUMBER_LOOKEAHEAD), Term.alternative(rules.namedWithAlias(floatLiteral, literal), rules.named(integerLiteral))),
|
| 659 | Term.sequence(Term.positiveLookahead(StringReaderTerms.characters('"', '\'')), Term.cut(), rules.named(quotedStringLiteral)),
|
| 660 | Term.sequence(Term.positiveLookahead(StringReaderTerms.character('{')), Term.cut(), rules.namedWithAlias(mapLiteral, literal)),
|
| 661 | Term.sequence(Term.positiveLookahead(StringReaderTerms.character('[')), Term.cut(), rules.namedWithAlias(listLiteral, literal)),
|
| 662 | rules.namedWithAlias(unquotedStringOrBuiltIn, literal)
|
| 663 | ),
|
| 664 | state -> {
|
| 665 | Scope scope = state.scope();
|
| 666 | String quotedString = scope.get(quotedStringLiteral);
|
| 667 | if (quotedString != null) {
|
| 668 | return ops.createString(quotedString);
|
| 669 | }
|
| 670 |
|
| 671 | SnbtGrammar.IntegerLiteral integer = scope.get(integerLiteral);
|
| 672 | return integer != null ? integer.create(ops, state) : scope.getOrThrow(literal);
|
| 673 | }
|
| 674 | );
|
| 675 | return new Grammar<>(rules, literalRule);
|
| 676 | }
|
| 677 |
|
| 678 | private enum ArrayPrefix {
|
| 679 | BYTE(SnbtGrammar.TypeSuffix.BYTE) {
|
| 680 | private static final ByteBuffer EMPTY_BUFFER = ByteBuffer.wrap(new byte[0]);
|
| 681 |
|
| 682 | @Override
|
| 683 | public <T> T create(final DynamicOps<T> ops) {
|
| 684 | return ops.createByteList(EMPTY_BUFFER);
|
| 685 | }
|
| 686 |
|
| 687 | @Override
|
| 688 | public <T> @Nullable T create(final DynamicOps<T> ops, final List<SnbtGrammar.IntegerLiteral> entries, final ParseState<?> state) {
|
| 689 | ByteList result = new ByteArrayList();
|
| 690 |
|
| 691 | for (SnbtGrammar.IntegerLiteral entry : entries) {
|
| 692 | Number parsedNumber = this.buildNumber(entry, state);
|
| 693 | if (parsedNumber == null) {
|
| 694 | return null;
|
| 695 | }
|
| 696 |
|
| 697 | result.add(parsedNumber.byteValue());
|
| 698 | }
|
| 699 |
|
| 700 | return ops.createByteList(ByteBuffer.wrap(result.toByteArray()));
|
| 701 | }
|
| 702 | },
|
| 703 | INT(SnbtGrammar.TypeSuffix.INT, SnbtGrammar.TypeSuffix.BYTE, SnbtGrammar.TypeSuffix.SHORT) {
|
| 704 | @Override
|
| 705 | public <T> T create(final DynamicOps<T> ops) {
|
| 706 | return ops.createIntList(IntStream.empty());
|
| 707 | }
|
| 708 |
|
| 709 | @Override
|
| 710 | public <T> @Nullable T create(final DynamicOps<T> ops, final List<SnbtGrammar.IntegerLiteral> entries, final ParseState<?> state) {
|
| 711 | java.util.stream.IntStream.Builder result = IntStream.builder();
|
| 712 |
|
| 713 | for (SnbtGrammar.IntegerLiteral entry : entries) {
|
| 714 | Number parsedNumber = this.buildNumber(entry, state);
|
| 715 | if (parsedNumber == null) {
|
| 716 | return null;
|
| 717 | }
|
| 718 |
|
| 719 | result.add(parsedNumber.intValue());
|
| 720 | }
|
| 721 |
|
| 722 | return ops.createIntList(result.build());
|
| 723 | }
|
| 724 | },
|
| 725 | LONG(SnbtGrammar.TypeSuffix.LONG, SnbtGrammar.TypeSuffix.BYTE, SnbtGrammar.TypeSuffix.SHORT, SnbtGrammar.TypeSuffix.INT) {
|
| 726 | @Override
|
| 727 | public <T> T create(final DynamicOps<T> ops) {
|
| 728 | return ops.createLongList(LongStream.empty());
|
| 729 | }
|
| 730 |
|
| 731 | @Override
|
| 732 | public <T> @Nullable T create(final DynamicOps<T> ops, final List<SnbtGrammar.IntegerLiteral> entries, final ParseState<?> state) {
|
| 733 | java.util.stream.LongStream.Builder result = LongStream.builder();
|
| 734 |
|
| 735 | for (SnbtGrammar.IntegerLiteral entry : entries) {
|
| 736 | Number parsedNumber = this.buildNumber(entry, state);
|
| 737 | if (parsedNumber == null) {
|
| 738 | return null;
|
| 739 | }
|
| 740 |
|
| 741 | result.add(parsedNumber.longValue());
|
| 742 | }
|
| 743 |
|
| 744 | return ops.createLongList(result.build());
|
| 745 | }
|
| 746 | };
|
| 747 |
|
| 748 | private final SnbtGrammar.TypeSuffix defaultType;
|
| 749 | private final Set<SnbtGrammar.TypeSuffix> additionalTypes;
|
| 750 |
|
| 751 | ArrayPrefix(final SnbtGrammar.TypeSuffix defaultType, final SnbtGrammar.TypeSuffix... additionalTypes) {
|
| 752 | this.additionalTypes = Set.of(additionalTypes);
|
| 753 | this.defaultType = defaultType;
|
| 754 | }
|
| 755 |
|
| 756 | public boolean isAllowed(final SnbtGrammar.TypeSuffix type) {
|
| 757 | return type == this.defaultType || this.additionalTypes.contains(type);
|
| 758 | }
|
| 759 |
|
| 760 | public abstract <T> T create(DynamicOps<T> ops);
|
| 761 |
|
| 762 | public abstract <T> @Nullable T create(DynamicOps<T> ops, List<SnbtGrammar.IntegerLiteral> entries, ParseState<?> state);
|
| 763 |
|
| 764 | protected @Nullable Number buildNumber(final SnbtGrammar.IntegerLiteral entry, final ParseState<?> state) {
|
| 765 | SnbtGrammar.TypeSuffix actualType = this.computeType(entry.suffix);
|
| 766 | if (actualType == null) {
|
| 767 | state.errorCollector().store(state.mark(), SnbtGrammar.ERROR_INVALID_ARRAY_ELEMENT_TYPE);
|
| 768 | return null;
|
| 769 | } else {
|
| 770 | return (Number)entry.create(JavaOps.INSTANCE, actualType, state);
|
| 771 | }
|
| 772 | }
|
| 773 |
|
| 774 | private SnbtGrammar.@Nullable TypeSuffix computeType(final SnbtGrammar.IntegerSuffix value) {
|
| 775 | SnbtGrammar.TypeSuffix type = value.type();
|
| 776 | if (type == null) {
|
| 777 | return this.defaultType;
|
| 778 | } else {
|
| 779 | return !this.isAllowed(type) ? null : type;
|
| 780 | }
|
| 781 | }
|
| 782 | }
|
| 783 |
|
| 784 | private enum Base {
|
| 785 | BINARY,
|
| 786 | DECIMAL,
|
| 787 | HEX;
|
| 788 | }
|
| 789 |
|
| 790 | private record IntegerLiteral(SnbtGrammar.Sign sign, SnbtGrammar.Base base, String digits, SnbtGrammar.IntegerSuffix suffix) {
|
| 791 | private SnbtGrammar.SignedPrefix signedOrDefault() {
|
| 792 | if (this.suffix.signed != null) {
|
| 793 | return this.suffix.signed;
|
| 794 | }
|
| 795 |
|
| 796 | return switch (this.base) {
|
| 797 | case BINARY, HEX -> SnbtGrammar.SignedPrefix.UNSIGNED;
|
| 798 | case DECIMAL -> SnbtGrammar.SignedPrefix.SIGNED;
|
| 799 | };
|
| 800 | }
|
| 801 |
|
| 802 | private String cleanupDigits(final SnbtGrammar.Sign sign) {
|
| 803 | boolean needsUnderscoreRemoval = SnbtGrammar.needsUnderscoreRemoval(this.digits);
|
| 804 | if (sign != SnbtGrammar.Sign.MINUS && !needsUnderscoreRemoval) {
|
| 805 | return this.digits;
|
| 806 | }
|
| 807 |
|
| 808 | StringBuilder result = new StringBuilder();
|
| 809 | sign.append(result);
|
| 810 | SnbtGrammar.cleanAndAppend(result, this.digits, needsUnderscoreRemoval);
|
| 811 | return result.toString();
|
| 812 | }
|
| 813 |
|
| 814 | public <T> @Nullable T create(final DynamicOps<T> ops, final ParseState<?> state) {
|
| 815 | return this.create(ops, Objects.requireNonNullElse(this.suffix.type, SnbtGrammar.TypeSuffix.INT), state);
|
| 816 | }
|
| 817 |
|
| 818 | public <T> @Nullable T create(final DynamicOps<T> ops, final SnbtGrammar.TypeSuffix type, final ParseState<?> state) {
|
| 819 | boolean isSigned = this.signedOrDefault() == SnbtGrammar.SignedPrefix.SIGNED;
|
| 820 | if (!isSigned && this.sign == SnbtGrammar.Sign.MINUS) {
|
| 821 | state.errorCollector().store(state.mark(), SnbtGrammar.ERROR_EXPECTED_NON_NEGATIVE_NUMBER);
|
| 822 | return null;
|
| 823 | }
|
| 824 |
|
| 825 | String fixedDigits = this.cleanupDigits(this.sign);
|
| 826 |
|
| 827 | int radix = switch (this.base) {
|
| 828 | case BINARY -> 2;
|
| 829 | case DECIMAL -> 10;
|
| 830 | case HEX -> 16;
|
| 831 | };
|
| 832 |
|
| 833 | try {
|
| 834 | if (isSigned) {
|
| 835 | return (T)(switch (type) {
|
| 836 | case BYTE -> ops.createByte(Byte.parseByte(fixedDigits, radix));
|
| 837 | case SHORT -> ops.createShort(Short.parseShort(fixedDigits, radix));
|
| 838 | case INT -> ops.createInt(Integer.parseInt(fixedDigits, radix));
|
| 839 | case LONG -> ops.createLong(Long.parseLong(fixedDigits, radix));
|
| 840 | default -> {
|
| 841 | state.errorCollector().store(state.mark(), SnbtGrammar.ERROR_EXPECTED_INTEGER_TYPE);
|
| 842 | yield null;
|
| 843 | }
|
| 844 | });
|
| 845 | } else {
|
| 846 | return (T)(switch (type) {
|
| 847 | case BYTE -> ops.createByte(UnsignedBytes.parseUnsignedByte(fixedDigits, radix));
|
| 848 | case SHORT -> ops.createShort(SnbtGrammar.parseUnsignedShort(fixedDigits, radix));
|
| 849 | case INT -> ops.createInt(Integer.parseUnsignedInt(fixedDigits, radix));
|
| 850 | case LONG -> ops.createLong(Long.parseUnsignedLong(fixedDigits, radix));
|
| 851 | default -> {
|
| 852 | state.errorCollector().store(state.mark(), SnbtGrammar.ERROR_EXPECTED_INTEGER_TYPE);
|
| 853 | yield null;
|
| 854 | }
|
| 855 | });
|
| 856 | }
|
| 857 | } catch (NumberFormatException e) {
|
| 858 | state.errorCollector().store(state.mark(), SnbtGrammar.createNumberParseError(e));
|
| 859 | return null;
|
| 860 | }
|
| 861 | }
|
| 862 | }
|
| 863 |
|
| 864 | private record IntegerSuffix(SnbtGrammar.@Nullable SignedPrefix signed, SnbtGrammar.@Nullable TypeSuffix type) {
|
| 865 | public static final SnbtGrammar.IntegerSuffix EMPTY = new SnbtGrammar.IntegerSuffix(null, null);
|
| 866 | }
|
| 867 |
|
| 868 | private enum Sign {
|
| 869 | PLUS,
|
| 870 | MINUS;
|
| 871 |
|
| 872 | public void append(final StringBuilder output) {
|
| 873 | if (this == MINUS) {
|
| 874 | output.append("-");
|
| 875 | }
|
| 876 | }
|
| 877 | }
|
| 878 |
|
| 879 | private record Signed<T>(SnbtGrammar.Sign sign, T value) {
|
| 880 | }
|
| 881 |
|
| 882 | private enum SignedPrefix {
|
| 883 | SIGNED,
|
| 884 | UNSIGNED;
|
| 885 | }
|
| 886 |
|
| 887 | private static class SimpleHexLiteralParseRule extends GreedyPredicateParseRule {
|
| 888 | public SimpleHexLiteralParseRule(final int size) {
|
| 889 | super(size, size, DelayedException.create(SnbtGrammar.ERROR_EXPECTED_HEX_ESCAPE, String.valueOf(size)));
|
| 890 | }
|
| 891 |
|
| 892 | @Override
|
| 893 | protected boolean isAccepted(final char c) {
|
| 894 | return switch (c) {
|
| 895 | case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'a', 'b', 'c', 'd', 'e', 'f' -> true;
|
| 896 | default -> false;
|
| 897 | };
|
| 898 | }
|
| 899 | }
|
| 900 |
|
| 901 | private enum TypeSuffix {
|
| 902 | FLOAT,
|
| 903 | DOUBLE,
|
| 904 | BYTE,
|
| 905 | SHORT,
|
| 906 | INT,
|
| 907 | LONG;
|
| 908 | }
|
| 909 | }
|
| 910 |
|