diff --git a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/SnbtGrammar.java b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/SnbtGrammar.java index 4415e2655..74512176c 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/SnbtGrammar.java +++ b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/SnbtGrammar.java @@ -124,8 +124,8 @@ public class SnbtGrammar { }; private static final Pattern UNICODE_NAME = Pattern.compile("[-a-zA-Z0-9 ]+"); - static DelayedException createNumberParseError(NumberFormatException numberFormatException) { - return DelayedException.create(ERROR_NUMBER_PARSE_FAILURE, numberFormatException.getMessage()); + static DelayedException createNumberParseError(NumberFormatException ex) { + return DelayedException.create(ERROR_NUMBER_PARSE_FAILURE, ex.getMessage()); } private static boolean isAllowedToStartUnquotedString(char c) { @@ -139,96 +139,97 @@ public class SnbtGrammar { }; } - static boolean needsUnderscoreRemoval(String text) { - return text.indexOf(95) != -1; + static boolean needsUnderscoreRemoval(String contents) { + return contents.indexOf(95) != -1; } - private static void cleanAndAppend(StringBuilder stringBuilder, String text) { - cleanAndAppend(stringBuilder, text, needsUnderscoreRemoval(text)); + private static void cleanAndAppend(StringBuilder output, String contents) { + cleanAndAppend(output, contents, needsUnderscoreRemoval(contents)); } - static void cleanAndAppend(StringBuilder stringBuilder, String text, boolean removeUnderscores) { - if (removeUnderscores) { - for (char c : text.toCharArray()) { + static void cleanAndAppend(StringBuilder output, String contents, boolean needsUnderscoreRemoval) { + if (needsUnderscoreRemoval) { + for (char c : contents.toCharArray()) { if (c != '_') { - stringBuilder.append(c); + output.append(c); } } + return; } - stringBuilder.append(text); + output.append(contents); } - static short parseUnsignedShort(String text, int radix) { - int i = Integer.parseInt(text, radix); - if (i >> 16 == 0) { - return (short)i; + static short parseUnsignedShort(String string, int radix) { + int parse = Integer.parseInt(string, radix); + if (parse >> 16 == 0) { + return (short) parse; } - throw new NumberFormatException("out of range: " + i); + throw new NumberFormatException("out of range: " + parse); } @Nullable private static T createFloat( DynamicOps ops, Sign sign, - @Nullable String wholePart, - @Nullable String fractionPart, - @Nullable Signed exponentPart, - @Nullable TypeSuffix suffix, - ParseState parseState + @Nullable String whole, + @Nullable String fraction, + @Nullable Signed exponent, + @Nullable TypeSuffix typeSuffix, + ParseState state ) { - StringBuilder stringBuilder = new StringBuilder(); - sign.append(stringBuilder); - if (wholePart != null) { - cleanAndAppend(stringBuilder, wholePart); + StringBuilder result = new StringBuilder(); + sign.append(result); + if (whole != null) { + cleanAndAppend(result, whole); } - if (fractionPart != null) { - stringBuilder.append('.'); - cleanAndAppend(stringBuilder, fractionPart); + if (fraction != null) { + result.append('.'); + cleanAndAppend(result, fraction); } - if (exponentPart != null) { - stringBuilder.append('e'); - exponentPart.sign().append(stringBuilder); - cleanAndAppend(stringBuilder, exponentPart.value); + if (exponent != null) { + result.append('e'); + exponent.sign().append(result); + cleanAndAppend(result, exponent.value); } try { - String string = stringBuilder.toString(); + String string = result.toString(); - return switch (suffix) { - case null -> convertDouble(ops, parseState, string); - case FLOAT -> convertFloat(ops, parseState, string); - case DOUBLE -> convertDouble(ops, parseState, string); + return switch (typeSuffix) { + case null -> convertDouble(ops, state, string); + case FLOAT -> convertFloat(ops, state, string); + case DOUBLE -> convertDouble(ops, state, string); default -> { - parseState.errorCollector().store(parseState.mark(), ERROR_EXPECTED_FLOAT_TYPE); + state.errorCollector().store(state.mark(), ERROR_EXPECTED_FLOAT_TYPE); yield null; } }; - } catch (NumberFormatException var11) { - parseState.errorCollector().store(parseState.mark(), createNumberParseError(var11)); + } catch (NumberFormatException e) { + state.errorCollector().store(state.mark(), createNumberParseError(e)); return null; } } @Nullable - private static T convertFloat(DynamicOps ops, ParseState parseState, String value) { - float f = Float.parseFloat(value); - if (!Float.isFinite(f)) { - parseState.errorCollector().store(parseState.mark(), ERROR_INFINITY_NOT_ALLOWED); + private static T convertFloat(DynamicOps ops, ParseState state, String contents) { + float value = Float.parseFloat(contents); + if (!Float.isFinite(value)) { + state.errorCollector().store(state.mark(), ERROR_INFINITY_NOT_ALLOWED); return null; } - return ops.createFloat(f); + return ops.createFloat(value); } @Nullable - private static T convertDouble(DynamicOps ops, ParseState parseState, String value) { - double d = Double.parseDouble(value); - if (!Double.isFinite(d)) { - parseState.errorCollector().store(parseState.mark(), ERROR_INFINITY_NOT_ALLOWED); + private static T convertDouble(DynamicOps ops, ParseState state, String contents) { + double value = Double.parseDouble(contents); + if (!Double.isFinite(value)) { + state.errorCollector().store(state.mark(), ERROR_INFINITY_NOT_ALLOWED); return null; } - return ops.createDouble(d); + return ops.createDouble(value); } private static String joinList(List list) { @@ -241,42 +242,44 @@ public class SnbtGrammar { @SuppressWarnings("unchecked") public static Grammar createParser(DynamicOps ops) { - T object = ops.createBoolean(true); - T object1 = ops.createBoolean(false); - T object2 = ops.emptyMap(); - T object3 = ops.emptyList(); - Dictionary dictionary = new Dictionary<>(); - Atom atom = Atom.of("sign"); - dictionary.put( - atom, + T trueValue = ops.createBoolean(true); + T falseValue = ops.createBoolean(false); + T emptyMapValue = ops.emptyMap(); + T emptyList = ops.emptyList(); + T nullString = ops.createString("null"); + boolean isJavaType = "null".equals(nullString); // 确定是 Java 类型的 + Dictionary rules = new Dictionary<>(); + Atom sign = Atom.of("sign"); + rules.put( + sign, Term.alternative( - Term.sequence(StringReaderTerms.character('+'), Term.marker(atom, Sign.PLUS)), - Term.sequence(StringReaderTerms.character('-'), Term.marker(atom, Sign.MINUS)) + Term.sequence(StringReaderTerms.character('+'), Term.marker(sign, Sign.PLUS)), + Term.sequence(StringReaderTerms.character('-'), Term.marker(sign, Sign.MINUS)) ), - scope -> scope.getOrThrow(atom) + scope -> scope.getOrThrow(sign) ); - Atom atom1 = Atom.of("integer_suffix"); - dictionary.put( - atom1, + Atom integerSuffix = Atom.of("integer_suffix"); + rules.put( + integerSuffix, Term.alternative( Term.sequence( StringReaderTerms.characters('u', 'U'), Term.alternative( Term.sequence( StringReaderTerms.characters('b', 'B'), - Term.marker(atom1, new IntegerSuffix(SignedPrefix.UNSIGNED, TypeSuffix.BYTE)) + Term.marker(integerSuffix, new IntegerSuffix(SignedPrefix.UNSIGNED, TypeSuffix.BYTE)) ), Term.sequence( StringReaderTerms.characters('s', 'S'), - Term.marker(atom1, new IntegerSuffix(SignedPrefix.UNSIGNED, TypeSuffix.SHORT)) + Term.marker(integerSuffix, new IntegerSuffix(SignedPrefix.UNSIGNED, TypeSuffix.SHORT)) ), Term.sequence( StringReaderTerms.characters('i', 'I'), - Term.marker(atom1, new IntegerSuffix(SignedPrefix.UNSIGNED, TypeSuffix.INT)) + Term.marker(integerSuffix, new IntegerSuffix(SignedPrefix.UNSIGNED, TypeSuffix.INT)) ), Term.sequence( StringReaderTerms.characters('l', 'L'), - Term.marker(atom1, new IntegerSuffix(SignedPrefix.UNSIGNED, TypeSuffix.LONG)) + Term.marker(integerSuffix, new IntegerSuffix(SignedPrefix.UNSIGNED, TypeSuffix.LONG)) ) ) ), @@ -285,351 +288,349 @@ public class SnbtGrammar { Term.alternative( Term.sequence( StringReaderTerms.characters('b', 'B'), - Term.marker(atom1, new IntegerSuffix(SignedPrefix.SIGNED, TypeSuffix.BYTE)) + Term.marker(integerSuffix, new IntegerSuffix(SignedPrefix.SIGNED, TypeSuffix.BYTE)) ), Term.sequence( StringReaderTerms.characters('s', 'S'), - Term.marker(atom1, new IntegerSuffix(SignedPrefix.SIGNED, TypeSuffix.SHORT)) + Term.marker(integerSuffix, new IntegerSuffix(SignedPrefix.SIGNED, TypeSuffix.SHORT)) ), Term.sequence( StringReaderTerms.characters('i', 'I'), - Term.marker(atom1, new IntegerSuffix(SignedPrefix.SIGNED, TypeSuffix.INT)) + Term.marker(integerSuffix, new IntegerSuffix(SignedPrefix.SIGNED, TypeSuffix.INT)) ), Term.sequence( StringReaderTerms.characters('l', 'L'), - Term.marker(atom1, new IntegerSuffix(SignedPrefix.SIGNED, TypeSuffix.LONG)) + Term.marker(integerSuffix, new IntegerSuffix(SignedPrefix.SIGNED, TypeSuffix.LONG)) ) ) ), - Term.sequence(StringReaderTerms.characters('b', 'B'), Term.marker(atom1, new IntegerSuffix(null, TypeSuffix.BYTE))), - Term.sequence(StringReaderTerms.characters('s', 'S'), Term.marker(atom1, new IntegerSuffix(null, TypeSuffix.SHORT))), - Term.sequence(StringReaderTerms.characters('i', 'I'), Term.marker(atom1, new IntegerSuffix(null, TypeSuffix.INT))), - Term.sequence(StringReaderTerms.characters('l', 'L'), Term.marker(atom1, new IntegerSuffix(null, TypeSuffix.LONG))) + Term.sequence(StringReaderTerms.characters('b', 'B'), Term.marker(integerSuffix, new IntegerSuffix(null, TypeSuffix.BYTE))), + Term.sequence(StringReaderTerms.characters('s', 'S'), Term.marker(integerSuffix, new IntegerSuffix(null, TypeSuffix.SHORT))), + Term.sequence(StringReaderTerms.characters('i', 'I'), Term.marker(integerSuffix, new IntegerSuffix(null, TypeSuffix.INT))), + Term.sequence(StringReaderTerms.characters('l', 'L'), Term.marker(integerSuffix, new IntegerSuffix(null, TypeSuffix.LONG))) ), - scope -> scope.getOrThrow(atom1) + scope -> scope.getOrThrow(integerSuffix) ); - Atom atom2 = Atom.of("binary_numeral"); - dictionary.put(atom2, BINARY_NUMERAL); - Atom atom3 = Atom.of("decimal_numeral"); - dictionary.put(atom3, DECIMAL_NUMERAL); - Atom atom4 = Atom.of("hex_numeral"); - dictionary.put(atom4, HEX_NUMERAL); - Atom atom5 = Atom.of("integer_literal"); - NamedRule namedRule = dictionary.put( - atom5, + Atom binaryNumeral = Atom.of("binary_numeral"); + rules.put(binaryNumeral, BINARY_NUMERAL); + Atom decimalNumeral = Atom.of("decimal_numeral"); + rules.put(decimalNumeral, DECIMAL_NUMERAL); + Atom hexNumeral = Atom.of("hex_numeral"); + rules.put(hexNumeral, HEX_NUMERAL); + Atom integerLiteral = Atom.of("integer_literal"); + NamedRule integerLiteralRule = rules.put( + integerLiteral, Term.sequence( - Term.optional(dictionary.named(atom)), + Term.optional(rules.named(sign)), Term.alternative( Term.sequence( StringReaderTerms.character('0'), Term.cut(), Term.alternative( - Term.sequence(StringReaderTerms.characters('x', 'X'), Term.cut(), dictionary.named(atom4)), - Term.sequence(StringReaderTerms.characters('b', 'B'), dictionary.named(atom2)), - Term.sequence(dictionary.named(atom3), Term.cut(), Term.fail(ERROR_LEADING_ZERO_NOT_ALLOWED)), - Term.marker(atom3, "0") + Term.sequence(StringReaderTerms.characters('x', 'X'), Term.cut(), rules.named(hexNumeral)), + Term.sequence(StringReaderTerms.characters('b', 'B'), rules.named(binaryNumeral)), + Term.sequence(rules.named(decimalNumeral), Term.cut(), Term.fail(ERROR_LEADING_ZERO_NOT_ALLOWED)), + Term.marker(decimalNumeral, "0") ) ), - dictionary.named(atom3) + rules.named(decimalNumeral) ), - Term.optional(dictionary.named(atom1)) + Term.optional(rules.named(integerSuffix)) ), scope -> { - IntegerSuffix integerSuffix = scope.getOrDefault(atom1, IntegerSuffix.EMPTY); - Sign sign = scope.getOrDefault(atom, Sign.PLUS); - String string = scope.get(atom3); - if (string != null) { - return new IntegerLiteral(sign, Base.DECIMAL, string, integerSuffix); + IntegerSuffix suffix = scope.getOrDefault(integerSuffix, IntegerSuffix.EMPTY); + Sign signValue = scope.getOrDefault(sign, Sign.PLUS); + String decimalContents = scope.get(decimalNumeral); + if (decimalContents != null) { + return new IntegerLiteral(signValue, Base.DECIMAL, decimalContents, suffix); } - String string1 = scope.get(atom4); + String string1 = scope.get(hexNumeral); if (string1 != null) { - return new IntegerLiteral(sign, Base.HEX, string1, integerSuffix); + return new IntegerLiteral(signValue, Base.HEX, string1, suffix); } - String string2 = scope.getOrThrow(atom2); - return new IntegerLiteral(sign, Base.BINARY, string2, integerSuffix); + String string2 = scope.getOrThrow(binaryNumeral); + return new IntegerLiteral(signValue, Base.BINARY, string2, suffix); } ); - Atom atom6 = Atom.of("float_type_suffix"); - dictionary.put( - atom6, + Atom floatTypeSuffix = Atom.of("float_type_suffix"); + rules.put( + floatTypeSuffix, Term.alternative( - Term.sequence(StringReaderTerms.characters('f', 'F'), Term.marker(atom6, TypeSuffix.FLOAT)), - Term.sequence(StringReaderTerms.characters('d', 'D'), Term.marker(atom6, TypeSuffix.DOUBLE)) + Term.sequence(StringReaderTerms.characters('f', 'F'), Term.marker(floatTypeSuffix, TypeSuffix.FLOAT)), + Term.sequence(StringReaderTerms.characters('d', 'D'), Term.marker(floatTypeSuffix, TypeSuffix.DOUBLE)) ), - scope -> scope.getOrThrow(atom6) + scope -> scope.getOrThrow(floatTypeSuffix) ); - Atom> atom7 = Atom.of("float_exponent_part"); - dictionary.put( - atom7, - Term.sequence(StringReaderTerms.characters('e', 'E'), Term.optional(dictionary.named(atom)), dictionary.named(atom3)), - scope -> new Signed<>(scope.getOrDefault(atom, Sign.PLUS), scope.getOrThrow(atom3)) + Atom> floatExponentPart = Atom.of("float_exponent_part"); + rules.put( + floatExponentPart, + Term.sequence(StringReaderTerms.characters('e', 'E'), Term.optional(rules.named(sign)), rules.named(decimalNumeral)), + scope -> new Signed<>(scope.getOrDefault(sign, Sign.PLUS), scope.getOrThrow(decimalNumeral)) ); - Atom atom8 = Atom.of("float_whole_part"); - Atom atom9 = Atom.of("float_fraction_part"); - Atom atom10 = Atom.of("float_literal"); - dictionary.putComplex( - atom10, + Atom floatWholePart = Atom.of("float_whole_part"); + Atom floatFractionPart = Atom.of("float_fraction_part"); + Atom floatLiteral = Atom.of("float_literal"); + rules.putComplex( + floatLiteral, Term.sequence( - Term.optional(dictionary.named(atom)), + Term.optional(rules.named(sign)), Term.alternative( Term.sequence( - dictionary.namedWithAlias(atom3, atom8), + rules.namedWithAlias(decimalNumeral, floatWholePart), StringReaderTerms.character('.'), Term.cut(), - Term.optional(dictionary.namedWithAlias(atom3, atom9)), - Term.optional(dictionary.named(atom7)), - Term.optional(dictionary.named(atom6)) + Term.optional(rules.namedWithAlias(decimalNumeral, floatFractionPart)), + Term.optional(rules.named(floatExponentPart)), + Term.optional(rules.named(floatTypeSuffix)) ), Term.sequence( StringReaderTerms.character('.'), Term.cut(), - dictionary.namedWithAlias(atom3, atom9), - Term.optional(dictionary.named(atom7)), - Term.optional(dictionary.named(atom6)) + rules.namedWithAlias(decimalNumeral, floatFractionPart), + Term.optional(rules.named(floatExponentPart)), + Term.optional(rules.named(floatTypeSuffix)) ), - Term.sequence(dictionary.namedWithAlias(atom3, atom8), dictionary.named(atom7), Term.cut(), Term.optional(dictionary.named(atom6))), - Term.sequence(dictionary.namedWithAlias(atom3, atom8), Term.optional(dictionary.named(atom7)), dictionary.named(atom6)) + Term.sequence(rules.namedWithAlias(decimalNumeral, floatWholePart), rules.named(floatExponentPart), Term.cut(), Term.optional(rules.named(floatTypeSuffix))), + Term.sequence(rules.namedWithAlias(decimalNumeral, floatWholePart), Term.optional(rules.named(floatExponentPart)), rules.named(floatTypeSuffix)) ) ), - parseState -> { - Scope scope = parseState.scope(); - Sign sign = scope.getOrDefault(atom, Sign.PLUS); - String string = scope.get(atom8); - String string1 = scope.get(atom9); - Signed signed = scope.get(atom7); - TypeSuffix typeSuffix = scope.get(atom6); - return createFloat(ops, sign, string, string1, signed, typeSuffix, parseState); + state -> { + Scope scope = state.scope(); + Sign wholeSign = scope.getOrDefault(sign, Sign.PLUS); + String whole = scope.get(floatWholePart); + String fraction = scope.get(floatFractionPart); + Signed exponent = scope.get(floatExponentPart); + TypeSuffix typeSuffix = scope.get(floatTypeSuffix); + return createFloat(ops, wholeSign, whole, fraction, exponent, typeSuffix, state); } ); - Atom atom11 = Atom.of("string_hex_2"); - dictionary.put(atom11, new SimpleHexLiteralParseRule(2)); - Atom atom12 = Atom.of("string_hex_4"); - dictionary.put(atom12, new SimpleHexLiteralParseRule(4)); - Atom atom13 = Atom.of("string_hex_8"); - dictionary.put(atom13, new SimpleHexLiteralParseRule(8)); - Atom atom14 = Atom.of("string_unicode_name"); - dictionary.put(atom14, new GreedyPatternParseRule(UNICODE_NAME, ERROR_INVALID_CHARACTER_NAME)); - Atom atom15 = Atom.of("string_escape_sequence"); - dictionary.putComplex( - atom15, + Atom stringHex2 = Atom.of("string_hex_2"); + rules.put(stringHex2, new SimpleHexLiteralParseRule(2)); + Atom stringHex4 = Atom.of("string_hex_4"); + rules.put(stringHex4, new SimpleHexLiteralParseRule(4)); + Atom stringHex8 = Atom.of("string_hex_8"); + rules.put(stringHex8, new SimpleHexLiteralParseRule(8)); + Atom stringUnicodeName = Atom.of("string_unicode_name"); + rules.put(stringUnicodeName, new GreedyPatternParseRule(UNICODE_NAME, ERROR_INVALID_CHARACTER_NAME)); + Atom stringEscapeSequence = Atom.of("string_escape_sequence"); + rules.putComplex( + stringEscapeSequence, Term.alternative( - Term.sequence(StringReaderTerms.character('b'), Term.marker(atom15, "\b")), - Term.sequence(StringReaderTerms.character('s'), Term.marker(atom15, " ")), - Term.sequence(StringReaderTerms.character('t'), Term.marker(atom15, "\t")), - Term.sequence(StringReaderTerms.character('n'), Term.marker(atom15, "\n")), - Term.sequence(StringReaderTerms.character('f'), Term.marker(atom15, "\f")), - Term.sequence(StringReaderTerms.character('r'), Term.marker(atom15, "\r")), - Term.sequence(StringReaderTerms.character('\\'), Term.marker(atom15, "\\")), - Term.sequence(StringReaderTerms.character('\''), Term.marker(atom15, "'")), - Term.sequence(StringReaderTerms.character('"'), Term.marker(atom15, "\"")), - Term.sequence(StringReaderTerms.character('x'), dictionary.named(atom11)), - Term.sequence(StringReaderTerms.character('u'), dictionary.named(atom12)), - Term.sequence(StringReaderTerms.character('U'), dictionary.named(atom13)), - Term.sequence(StringReaderTerms.character('N'), StringReaderTerms.character('{'), dictionary.named(atom14), StringReaderTerms.character('}')) + Term.sequence(StringReaderTerms.character('b'), Term.marker(stringEscapeSequence, "\b")), + Term.sequence(StringReaderTerms.character('s'), Term.marker(stringEscapeSequence, " ")), + Term.sequence(StringReaderTerms.character('t'), Term.marker(stringEscapeSequence, "\t")), + Term.sequence(StringReaderTerms.character('n'), Term.marker(stringEscapeSequence, "\n")), + Term.sequence(StringReaderTerms.character('f'), Term.marker(stringEscapeSequence, "\f")), + Term.sequence(StringReaderTerms.character('r'), Term.marker(stringEscapeSequence, "\r")), + Term.sequence(StringReaderTerms.character('\\'), Term.marker(stringEscapeSequence, "\\")), + Term.sequence(StringReaderTerms.character('\''), Term.marker(stringEscapeSequence, "'")), + Term.sequence(StringReaderTerms.character('"'), Term.marker(stringEscapeSequence, "\"")), + Term.sequence(StringReaderTerms.character('x'), rules.named(stringHex2)), + Term.sequence(StringReaderTerms.character('u'), rules.named(stringHex4)), + Term.sequence(StringReaderTerms.character('U'), rules.named(stringHex8)), + Term.sequence(StringReaderTerms.character('N'), StringReaderTerms.character('{'), rules.named(stringUnicodeName), StringReaderTerms.character('}')) ), - parseState -> { - Scope scope = parseState.scope(); - String string = scope.getAny(atom15); - if (string != null) { - return string; + state -> { + Scope scope = state.scope(); + String plainEscape = scope.getAny(stringEscapeSequence); + if (plainEscape != null) { + return plainEscape; } - String string1 = scope.getAny(atom11, atom12, atom13); - if (string1 != null) { - int i = HexFormat.fromHexDigits(string1); - if (!Character.isValidCodePoint(i)) { - parseState.errorCollector() - .store(parseState.mark(), DelayedException.create(ERROR_INVALID_CODEPOINT, String.format(Locale.ROOT, "U+%08X", i))); + String hexEscape = scope.getAny(stringHex2, stringHex4, stringHex8); + if (hexEscape != null) { + int codePoint = HexFormat.fromHexDigits(hexEscape); + if (!Character.isValidCodePoint(codePoint)) { + state.errorCollector() + .store(state.mark(), DelayedException.create(ERROR_INVALID_CODEPOINT, String.format(Locale.ROOT, "U+%08X", codePoint))); return null; } - return Character.toString(i); + return Character.toString(codePoint); } - String string2 = scope.getOrThrow(atom14); + String character = scope.getOrThrow(stringUnicodeName); - int i1; + int codePoint; try { - i1 = Character.codePointOf(string2); + codePoint = Character.codePointOf(character); } catch (IllegalArgumentException var12x) { - parseState.errorCollector().store(parseState.mark(), ERROR_INVALID_CHARACTER_NAME); + state.errorCollector().store(state.mark(), ERROR_INVALID_CHARACTER_NAME); return null; } - return Character.toString(i1); + return Character.toString(codePoint); } ); - Atom atom16 = Atom.of("string_plain_contents"); - dictionary.put(atom16, PLAIN_STRING_CHUNK); - Atom> atom17 = Atom.of("string_chunks"); - Atom atom18 = Atom.of("string_contents"); - Atom atom19 = Atom.of("single_quoted_string_chunk"); - NamedRule namedRule1 = dictionary.put( - atom19, + Atom stringPlainContents = Atom.of("string_plain_contents"); + rules.put(stringPlainContents, PLAIN_STRING_CHUNK); + Atom> stringChunks = Atom.of("string_chunks"); + Atom stringContents = Atom.of("string_contents"); + Atom singleQuotedStringChunk = Atom.of("single_quoted_string_chunk"); + NamedRule namedRule1 = rules.put( + singleQuotedStringChunk, Term.alternative( - dictionary.namedWithAlias(atom16, atom18), - Term.sequence(StringReaderTerms.character('\\'), dictionary.namedWithAlias(atom15, atom18)), - Term.sequence(StringReaderTerms.character('"'), Term.marker(atom18, "\"")) + rules.namedWithAlias(stringPlainContents, stringContents), + Term.sequence(StringReaderTerms.character('\\'), rules.namedWithAlias(stringEscapeSequence, stringContents)), + Term.sequence(StringReaderTerms.character('"'), Term.marker(stringContents, "\"")) ), - scope -> scope.getOrThrow(atom18) + scope -> scope.getOrThrow(stringContents) ); - Atom atom20 = Atom.of("single_quoted_string_contents"); - dictionary.put(atom20, Term.repeated(namedRule1, atom17), scope -> joinList(scope.getOrThrow(atom17))); - Atom atom21 = Atom.of("double_quoted_string_chunk"); - NamedRule namedRule2 = dictionary.put( - atom21, + Atom singleQuotedStringContents = Atom.of("single_quoted_string_contents"); + rules.put(singleQuotedStringContents, Term.repeated(namedRule1, stringChunks), scope -> joinList(scope.getOrThrow(stringChunks))); + Atom doubleQuotedStringChunk = Atom.of("double_quoted_string_chunk"); + NamedRule namedRule2 = rules.put( + doubleQuotedStringChunk, Term.alternative( - dictionary.namedWithAlias(atom16, atom18), - Term.sequence(StringReaderTerms.character('\\'), dictionary.namedWithAlias(atom15, atom18)), - Term.sequence(StringReaderTerms.character('\''), Term.marker(atom18, "'")) + rules.namedWithAlias(stringPlainContents, stringContents), + Term.sequence(StringReaderTerms.character('\\'), rules.namedWithAlias(stringEscapeSequence, stringContents)), + Term.sequence(StringReaderTerms.character('\''), Term.marker(stringContents, "'")) ), - scope -> scope.getOrThrow(atom18) + scope -> scope.getOrThrow(stringContents) ); - Atom atom22 = Atom.of("double_quoted_string_contents"); - dictionary.put(atom22, Term.repeated(namedRule2, atom17), scope -> joinList(scope.getOrThrow(atom17))); - Atom atom23 = Atom.of("quoted_string_literal"); - dictionary.put( - atom23, + Atom doubleQuotedStringContents = Atom.of("double_quoted_string_contents"); + rules.put(doubleQuotedStringContents, Term.repeated(namedRule2, stringChunks), scope -> joinList(scope.getOrThrow(stringChunks))); + Atom quotedStringLiteral = Atom.of("quoted_string_literal"); + rules.put( + quotedStringLiteral, Term.alternative( Term.sequence( - StringReaderTerms.character('"'), Term.cut(), Term.optional(dictionary.namedWithAlias(atom22, atom18)), StringReaderTerms.character('"') + StringReaderTerms.character('"'), Term.cut(), Term.optional(rules.namedWithAlias(doubleQuotedStringContents, stringContents)), StringReaderTerms.character('"') ), - Term.sequence(StringReaderTerms.character('\''), Term.optional(dictionary.namedWithAlias(atom20, atom18)), StringReaderTerms.character('\'')) + Term.sequence(StringReaderTerms.character('\''), Term.optional(rules.namedWithAlias(singleQuotedStringContents, stringContents)), StringReaderTerms.character('\'')) ), - scope -> scope.getOrThrow(atom18) + scope -> scope.getOrThrow(stringContents) ); - Atom atom24 = Atom.of("unquoted_string"); - dictionary.put(atom24, new UnquotedStringParseRule(1, ERROR_EXPECTED_UNQUOTED_STRING)); - Atom atom25 = Atom.of("literal"); - Atom> atom26 = Atom.of("arguments"); - dictionary.put( - atom26, Term.repeatedWithTrailingSeparator(dictionary.forward(atom25), atom26, StringReaderTerms.character(TagParser.ELEMENT_SEPARATOR)), scope -> scope.getOrThrow(atom26) + Atom unquotedString = Atom.of("unquoted_string"); + rules.put(unquotedString, new UnquotedStringParseRule(1, ERROR_EXPECTED_UNQUOTED_STRING)); + Atom literal = Atom.of("literal"); + Atom> argumentList = Atom.of("arguments"); + rules.put( + argumentList, Term.repeatedWithTrailingSeparator(rules.forward(literal), argumentList, StringReaderTerms.character(TagParser.ELEMENT_SEPARATOR)), scope -> scope.getOrThrow(argumentList) ); - Atom atom27 = Atom.of("unquoted_string_or_builtin"); - dictionary.putComplex( - atom27, + Atom unquotedStringOrBuiltIn = Atom.of("unquoted_string_or_builtin"); + rules.putComplex( + unquotedStringOrBuiltIn, Term.sequence( - dictionary.named(atom24), - Term.optional(Term.sequence(StringReaderTerms.character('('), dictionary.named(atom26), StringReaderTerms.character(')'))) + rules.named(unquotedString), + Term.optional(Term.sequence(StringReaderTerms.character('('), rules.named(argumentList), StringReaderTerms.character(')'))) ), - parseState -> { - Scope scope = parseState.scope(); - String string = scope.getOrThrow(atom24); - if (!string.isEmpty() && isAllowedToStartUnquotedString(string.charAt(0))) { - List list = scope.get(atom26); - if (list != null) { - SnbtOperations.BuiltinKey builtinKey = new SnbtOperations.BuiltinKey(string, list.size()); - SnbtOperations.BuiltinOperation builtinOperation = SnbtOperations.BUILTIN_OPERATIONS.get(builtinKey); - if (builtinOperation != null) { - return builtinOperation.run(ops, list, parseState); + state -> { + Scope scope = state.scope(); + String contents = scope.getOrThrow(unquotedString); + if (!contents.isEmpty() && isAllowedToStartUnquotedString(contents.charAt(0))) { + List arguments = scope.get(argumentList); + if (arguments != null) { + SnbtOperations.BuiltinKey key = new SnbtOperations.BuiltinKey(contents, arguments.size()); + SnbtOperations.BuiltinOperation operation = SnbtOperations.BUILTIN_OPERATIONS.get(key); + if (operation != null) { + return operation.run(ops, arguments, state); } - parseState.errorCollector().store(parseState.mark(), DelayedException.create(ERROR_NO_SUCH_OPERATION, builtinKey.toString())); + state.errorCollector().store(state.mark(), DelayedException.create(ERROR_NO_SUCH_OPERATION, key.toString())); return null; - } else if (string.equalsIgnoreCase("true")) { - return object; - } else if (string.equalsIgnoreCase("false")) { - return object1; - } else if (string.equalsIgnoreCase("null")) { + } else if (contents.equalsIgnoreCase("true")) { + return trueValue; + } else if (contents.equalsIgnoreCase("false")) { + return falseValue; + } else if (contents.equalsIgnoreCase("null")) { return Objects.requireNonNullElseGet(ops.empty(), () -> { - T nullString = ops.createString("null"); - if ("null".equals(nullString)) { // 确定是 Java 类型的 + if (isJavaType) { return (T) CachedParseState.JAVA_NULL_VALUE_MARKER; } return nullString; }); } - return ops.createString(string); + return ops.createString(contents); } - parseState.errorCollector().store(parseState.mark(), SnbtOperations.BUILTIN_IDS, ERROR_INVALID_UNQUOTED_START); + state.errorCollector().store(state.mark(), SnbtOperations.BUILTIN_IDS, ERROR_INVALID_UNQUOTED_START); return null; } ); - Atom atom28 = Atom.of("map_key"); - dictionary.put(atom28, Term.alternative(dictionary.named(atom23), dictionary.named(atom24)), scope -> scope.getAnyOrThrow(atom23, atom24)); - Atom> atom29 = Atom.of("map_entry"); - NamedRule> namedRule3 = dictionary.putComplex( - atom29, Term.sequence(dictionary.named(atom28), StringReaderTerms.character(TagParser.NAME_VALUE_SEPARATOR), dictionary.named(atom25)), parseState -> { - Scope scope = parseState.scope(); - String string = scope.getOrThrow(atom28); - if (string.isEmpty()) { - parseState.errorCollector().store(parseState.mark(), ERROR_EMPTY_KEY); + Atom mapKey = Atom.of("map_key"); + rules.put(mapKey, Term.alternative(rules.named(quotedStringLiteral), rules.named(unquotedString)), scope -> scope.getAnyOrThrow(quotedStringLiteral, unquotedString)); + Atom> mapEntry = Atom.of("map_entry"); + NamedRule> mapEntryRule = rules.putComplex( + mapEntry, Term.sequence(rules.named(mapKey), StringReaderTerms.character(TagParser.NAME_VALUE_SEPARATOR), rules.named(literal)), state -> { + Scope scope = state.scope(); + String key = scope.getOrThrow(mapKey); + if (key.isEmpty()) { + state.errorCollector().store(state.mark(), ERROR_EMPTY_KEY); return null; } - T orThrow = scope.getOrThrow(atom25); - return Map.entry(string, orThrow); + T value = scope.getOrThrow(literal); + return Map.entry(key, value); } ); - Atom>> atom30 = Atom.of("map_entries"); - dictionary.put(atom30, Term.repeatedWithTrailingSeparator(namedRule3, atom30, StringReaderTerms.character(TagParser.ELEMENT_SEPARATOR)), scope -> scope.getOrThrow(atom30)); - Atom atom31 = Atom.of("map_literal"); - dictionary.put(atom31, Term.sequence(StringReaderTerms.character('{'), Scope.increaseDepth(), dictionary.named(atom30), Scope.decreaseDepth(), StringReaderTerms.character('}')), scope -> { - List> list = scope.getOrThrow(atom30); - if (list.isEmpty()) { - return object2; - } else { - Builder builder = ImmutableMap.builderWithExpectedSize(list.size()); - - for (Entry entry : list) { - builder.put(ops.createString(entry.getKey()), entry.getValue()); - } - - return ops.createMap(builder.buildKeepingLast()); + Atom>> mapEntries = Atom.of("map_entries"); + rules.put(mapEntries, Term.repeatedWithTrailingSeparator(mapEntryRule, mapEntries, StringReaderTerms.character(TagParser.ELEMENT_SEPARATOR)), scope -> scope.getOrThrow(mapEntries)); + Atom mapLiteral = Atom.of("map_literal"); + rules.put(mapLiteral, Term.sequence(StringReaderTerms.character('{'), Scope.increaseDepth(), rules.named(mapEntries), Scope.decreaseDepth(), StringReaderTerms.character('}')), scope -> { + List> entries = scope.getOrThrow(mapEntries); + if (entries.isEmpty()) { + return emptyMapValue; } + Builder builder = ImmutableMap.builderWithExpectedSize(entries.size()); + + for (Entry e : entries) { + builder.put(ops.createString(e.getKey()), e.getValue()); + } + + return ops.createMap(builder.buildKeepingLast()); }); - Atom> atom32 = Atom.of("list_entries"); - dictionary.put( - atom32, Term.repeatedWithTrailingSeparator(dictionary.forward(atom25), atom32, StringReaderTerms.character(TagParser.ELEMENT_SEPARATOR)), scope -> scope.getOrThrow(atom32) + Atom> listEntries = Atom.of("list_entries"); + rules.put( + listEntries, Term.repeatedWithTrailingSeparator(rules.forward(literal), listEntries, StringReaderTerms.character(TagParser.ELEMENT_SEPARATOR)), scope -> scope.getOrThrow(listEntries) ); - Atom atom33 = Atom.of("array_prefix"); - dictionary.put( - atom33, + Atom arrayPrefix = Atom.of("array_prefix"); + rules.put( + arrayPrefix, Term.alternative( - Term.sequence(StringReaderTerms.character('B'), Term.marker(atom33, ArrayPrefix.BYTE)), - Term.sequence(StringReaderTerms.character('L'), Term.marker(atom33, ArrayPrefix.LONG)), - Term.sequence(StringReaderTerms.character('I'), Term.marker(atom33, ArrayPrefix.INT)) + Term.sequence(StringReaderTerms.character('B'), Term.marker(arrayPrefix, ArrayPrefix.BYTE)), + Term.sequence(StringReaderTerms.character('L'), Term.marker(arrayPrefix, ArrayPrefix.LONG)), + Term.sequence(StringReaderTerms.character('I'), Term.marker(arrayPrefix, ArrayPrefix.INT)) ), - scope -> scope.getOrThrow(atom33) + scope -> scope.getOrThrow(arrayPrefix) ); - Atom> atom34 = Atom.of("int_array_entries"); - dictionary.put(atom34, Term.repeatedWithTrailingSeparator(namedRule, atom34, StringReaderTerms.character(TagParser.ELEMENT_SEPARATOR)), scope -> scope.getOrThrow(atom34)); - Atom atom35 = Atom.of("list_literal"); - dictionary.putComplex( - atom35, + Atom> intArrayEntries = Atom.of("int_array_entries"); + rules.put(intArrayEntries, Term.repeatedWithTrailingSeparator(integerLiteralRule, intArrayEntries, StringReaderTerms.character(TagParser.ELEMENT_SEPARATOR)), scope -> scope.getOrThrow(intArrayEntries)); + Atom listLiteral = Atom.of("list_literal"); + rules.putComplex( + listLiteral, Term.sequence( StringReaderTerms.character('['), Scope.increaseDepth(), - Term.alternative(Term.sequence(dictionary.named(atom33), StringReaderTerms.character(';'), dictionary.named(atom34)), dictionary.named(atom32)), + Term.alternative(Term.sequence(rules.named(arrayPrefix), StringReaderTerms.character(';'), rules.named(intArrayEntries)), rules.named(listEntries)), Scope.decreaseDepth(), StringReaderTerms.character(']') ), - parseState -> { - Scope scope = parseState.scope(); - ArrayPrefix arrayPrefix = scope.get(atom33); - if (arrayPrefix != null) { - List list = scope.getOrThrow(atom34); - return list.isEmpty() ? arrayPrefix.create(ops) : arrayPrefix.create(ops, list, parseState); + state -> { + Scope scope = state.scope(); + ArrayPrefix arrayType = scope.get(arrayPrefix); + if (arrayType != null) { + List entries = scope.getOrThrow(intArrayEntries); + return entries.isEmpty() ? arrayType.create(ops) : arrayType.create(ops, entries, state); } - List list = scope.getOrThrow(atom32); - return list.isEmpty() ? object3 : ops.createList(list.stream()); + List entries = scope.getOrThrow(listEntries); + return entries.isEmpty() ? emptyList : ops.createList(entries.stream()); } ); - NamedRule namedRule4 = dictionary.putComplex( - atom25, + NamedRule literalRule = rules.putComplex( + literal, Term.alternative( - Term.sequence(Term.positiveLookahead(NUMBER_LOOKEAHEAD), Term.alternative(dictionary.namedWithAlias(atom10, atom25), dictionary.named(atom5))), - Term.sequence(Term.positiveLookahead(StringReaderTerms.characters('"', '\'')), Term.cut(), dictionary.named(atom23)), - Term.sequence(Term.positiveLookahead(StringReaderTerms.character('{')), Term.cut(), dictionary.namedWithAlias(atom31, atom25)), - Term.sequence(Term.positiveLookahead(StringReaderTerms.character('[')), Term.cut(), dictionary.namedWithAlias(atom35, atom25)), - dictionary.namedWithAlias(atom27, atom25) + Term.sequence(Term.positiveLookahead(NUMBER_LOOKEAHEAD), Term.alternative(rules.namedWithAlias(floatLiteral, literal), rules.named(integerLiteral))), + Term.sequence(Term.positiveLookahead(StringReaderTerms.characters('"', '\'')), Term.cut(), rules.named(quotedStringLiteral)), + Term.sequence(Term.positiveLookahead(StringReaderTerms.character('{')), Term.cut(), rules.namedWithAlias(mapLiteral, literal)), + Term.sequence(Term.positiveLookahead(StringReaderTerms.character('[')), Term.cut(), rules.namedWithAlias(listLiteral, literal)), + rules.namedWithAlias(unquotedStringOrBuiltIn, literal) ), - parseState -> { - Scope scope = parseState.scope(); - String string = scope.get(atom23); - if (string != null) { - return ops.createString(string); + state -> { + Scope scope = state.scope(); + String quotedString = scope.get(quotedStringLiteral); + if (quotedString != null) { + return ops.createString(quotedString); } - IntegerLiteral integerLiteral = scope.get(atom5); - return integerLiteral != null ? integerLiteral.create(ops, parseState) : scope.getOrThrow(atom25); + IntegerLiteral integer = scope.get(integerLiteral); + return integer != null ? integer.create(ops, state) : scope.getOrThrow(literal); } ); - return new Grammar<>(dictionary, namedRule4); + return new Grammar<>(rules, literalRule); } enum ArrayPrefix { @@ -643,19 +644,19 @@ public class SnbtGrammar { @Nullable @Override - public T create(DynamicOps ops, List values, ParseState parseState) { - ByteList list = new ByteArrayList(); + public T create(DynamicOps ops, List entries, ParseState state) { + ByteList result = new ByteArrayList(); - for (IntegerLiteral integerLiteral : values) { - Number number = this.buildNumber(integerLiteral, parseState); + for (IntegerLiteral entry : entries) { + Number number = this.buildNumber(entry, state); if (number == null) { return null; } - list.add(number.byteValue()); + result.add(number.byteValue()); } - return ops.createByteList(ByteBuffer.wrap(list.toByteArray())); + return ops.createByteList(ByteBuffer.wrap(result.toByteArray())); } }, INT(TypeSuffix.INT, TypeSuffix.BYTE, TypeSuffix.SHORT) { @@ -666,19 +667,19 @@ public class SnbtGrammar { @Nullable @Override - public T create(DynamicOps ops, List values, ParseState parseState) { - IntStream.Builder builder = IntStream.builder(); + public T create(DynamicOps ops, List entries, ParseState state) { + IntStream.Builder result = IntStream.builder(); - for (IntegerLiteral integerLiteral : values) { - Number number = this.buildNumber(integerLiteral, parseState); - if (number == null) { + for (IntegerLiteral entry : entries) { + Number parsedNumber = this.buildNumber(entry, state); + if (parsedNumber == null) { return null; } - builder.add(number.intValue()); + result.add(parsedNumber.intValue()); } - return ops.createIntList(builder.build()); + return ops.createIntList(result.build()); } }, LONG(TypeSuffix.LONG, TypeSuffix.BYTE, TypeSuffix.SHORT, TypeSuffix.INT) { @@ -689,19 +690,19 @@ public class SnbtGrammar { @Nullable @Override - public T create(DynamicOps ops, List values, ParseState parseState) { - LongStream.Builder builder = LongStream.builder(); + public T create(DynamicOps ops, List entries, ParseState state) { + LongStream.Builder result = LongStream.builder(); - for (IntegerLiteral integerLiteral : values) { - Number number = this.buildNumber(integerLiteral, parseState); - if (number == null) { + for (IntegerLiteral entry : entries) { + Number parsedNumber = this.buildNumber(entry, state); + if (parsedNumber == null) { return null; } - builder.add(number.longValue()); + result.add(parsedNumber.longValue()); } - return ops.createLongList(builder.build()); + return ops.createLongList(result.build()); } }; @@ -713,32 +714,32 @@ public class SnbtGrammar { this.defaultType = defaultType; } - public boolean isAllowed(TypeSuffix suffix) { - return suffix == this.defaultType || this.additionalTypes.contains(suffix); + public boolean isAllowed(TypeSuffix type) { + return type == this.defaultType || this.additionalTypes.contains(type); } public abstract T create(DynamicOps ops); @Nullable - public abstract T create(DynamicOps ops, List values, ParseState parseState); + public abstract T create(DynamicOps ops, List entries, ParseState state); @Nullable - protected Number buildNumber(IntegerLiteral value, ParseState parseState) { - TypeSuffix typeSuffix = this.computeType(value.suffix); - if (typeSuffix == null) { - parseState.errorCollector().store(parseState.mark(), ERROR_INVALID_ARRAY_ELEMENT_TYPE); + protected Number buildNumber(IntegerLiteral entry, ParseState state) { + TypeSuffix actualType = this.computeType(entry.suffix); + if (actualType == null) { + state.errorCollector().store(state.mark(), ERROR_INVALID_ARRAY_ELEMENT_TYPE); return null; } - return (Number)value.create(JavaOps.INSTANCE, typeSuffix, parseState); + return (Number) entry.create(JavaOps.INSTANCE, actualType, state); } @Nullable - private TypeSuffix computeType(IntegerSuffix suffix) { - TypeSuffix typeSuffix = suffix.type(); - if (typeSuffix == null) { + private TypeSuffix computeType(IntegerSuffix value) { + TypeSuffix type = value.type(); + if (type == null) { return this.defaultType; } - return !this.isAllowed(typeSuffix) ? null : typeSuffix; + return !this.isAllowed(type) ? null : type; } } @@ -757,61 +758,61 @@ public class SnbtGrammar { } private String cleanupDigits(Sign sign) { - boolean flag = needsUnderscoreRemoval(this.digits); - if (sign != Sign.MINUS && !flag) { + boolean needsUnderscoreRemoval = needsUnderscoreRemoval(this.digits); + if (sign != Sign.MINUS && !needsUnderscoreRemoval) { return this.digits; } - StringBuilder stringBuilder = new StringBuilder(); - sign.append(stringBuilder); - cleanAndAppend(stringBuilder, this.digits, flag); - return stringBuilder.toString(); + StringBuilder result = new StringBuilder(); + sign.append(result); + cleanAndAppend(result, this.digits, needsUnderscoreRemoval); + return result.toString(); } @Nullable - public T create(DynamicOps ops, ParseState parseState) { - return this.create(ops, Objects.requireNonNullElse(this.suffix.type, TypeSuffix.INT), parseState); + public T create(DynamicOps ops, ParseState state) { + return this.create(ops, Objects.requireNonNullElse(this.suffix.type, TypeSuffix.INT), state); } @Nullable - public T create(DynamicOps ops, TypeSuffix typeSuffix, ParseState parseState) { - boolean flag = this.signedOrDefault() == SignedPrefix.SIGNED; - if (!flag && this.sign == Sign.MINUS) { - parseState.errorCollector().store(parseState.mark(), ERROR_EXPECTED_NON_NEGATIVE_NUMBER); + public T create(DynamicOps ops, TypeSuffix type, ParseState state) { + boolean isSigned = this.signedOrDefault() == SignedPrefix.SIGNED; + if (!isSigned && this.sign == Sign.MINUS) { + state.errorCollector().store(state.mark(), ERROR_EXPECTED_NON_NEGATIVE_NUMBER); return null; } - String string = this.cleanupDigits(this.sign); + String fixedDigits = this.cleanupDigits(this.sign); - int i = switch (this.base) { + int radix = switch (this.base) { case BINARY -> 2; case DECIMAL -> 10; case HEX -> 16; }; try { - if (flag) { - return switch (typeSuffix) { - case BYTE -> ops.createByte(Byte.parseByte(string, i)); - case SHORT -> ops.createShort(Short.parseShort(string, i)); - case INT -> ops.createInt(Integer.parseInt(string, i)); - case LONG -> ops.createLong(Long.parseLong(string, i)); + if (isSigned) { + return switch (type) { + case BYTE -> ops.createByte(Byte.parseByte(fixedDigits, radix)); + case SHORT -> ops.createShort(Short.parseShort(fixedDigits, radix)); + case INT -> ops.createInt(Integer.parseInt(fixedDigits, radix)); + case LONG -> ops.createLong(Long.parseLong(fixedDigits, radix)); default -> { - parseState.errorCollector().store(parseState.mark(), ERROR_EXPECTED_INTEGER_TYPE); + state.errorCollector().store(state.mark(), ERROR_EXPECTED_INTEGER_TYPE); yield null; } }; } - return switch (typeSuffix) { - case BYTE -> ops.createByte(com.google.common.primitives.UnsignedBytes.parseUnsignedByte(string, i)); - case SHORT -> ops.createShort(parseUnsignedShort(string, i)); - case INT -> ops.createInt(Integer.parseUnsignedInt(string, i)); - case LONG -> ops.createLong(Long.parseUnsignedLong(string, i)); + return switch (type) { + case BYTE -> ops.createByte(com.google.common.primitives.UnsignedBytes.parseUnsignedByte(fixedDigits, radix)); + case SHORT -> ops.createShort(parseUnsignedShort(fixedDigits, radix)); + case INT -> ops.createInt(Integer.parseUnsignedInt(fixedDigits, radix)); + case LONG -> ops.createLong(Long.parseUnsignedLong(fixedDigits, radix)); default -> { - parseState.errorCollector().store(parseState.mark(), ERROR_EXPECTED_INTEGER_TYPE); + state.errorCollector().store(state.mark(), ERROR_EXPECTED_INTEGER_TYPE); yield null; } }; } catch (NumberFormatException var8) { - parseState.errorCollector().store(parseState.mark(), createNumberParseError(var8)); + state.errorCollector().store(state.mark(), createNumberParseError(var8)); return null; } } @@ -825,9 +826,9 @@ public class SnbtGrammar { PLUS, MINUS; - public void append(StringBuilder stringBuilder) { + public void append(StringBuilder output) { if (this == MINUS) { - stringBuilder.append("-"); + output.append("-"); } } } @@ -841,8 +842,8 @@ public class SnbtGrammar { } static class SimpleHexLiteralParseRule extends GreedyPredicateParseRule { - public SimpleHexLiteralParseRule(int minSize) { - super(minSize, minSize, DelayedException.create(ERROR_EXPECTED_HEX_ESCAPE, String.valueOf(minSize))); + public SimpleHexLiteralParseRule(int size) { + super(size, size, DelayedException.create(ERROR_EXPECTED_HEX_ESCAPE, String.valueOf(size))); } @Override diff --git a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/SnbtOperations.java b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/SnbtOperations.java index 9c684725d..589426cad 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/SnbtOperations.java +++ b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/SnbtOperations.java @@ -26,44 +26,42 @@ public class SnbtOperations { public static final Map BUILTIN_OPERATIONS = Map.of( new BuiltinKey("bool", 1), new BuiltinOperation() { @Override - public T run(DynamicOps ops, List args, ParseState parseState) { - Boolean bool = convert(ops, args.getFirst()); - if (bool == null) { - parseState.errorCollector().store(parseState.mark(), SnbtOperations.ERROR_EXPECTED_NUMBER_OR_BOOLEAN); + public T run(DynamicOps ops, List arguments, ParseState state) { + Boolean result = convert(ops, arguments.getFirst()); + if (result == null) { + state.errorCollector().store(state.mark(), SnbtOperations.ERROR_EXPECTED_NUMBER_OR_BOOLEAN); return null; - } else { - return ops.createBoolean(bool); } + return ops.createBoolean(result); } @Nullable - private static Boolean convert(DynamicOps ops, T value) { - Optional optional = ops.getBooleanValue(value).result(); - if (optional.isPresent()) { - return optional.get(); + private static Boolean convert(DynamicOps ops, T arg) { + Optional asBoolean = ops.getBooleanValue(arg).result(); + if (asBoolean.isPresent()) { + return asBoolean.get(); } else { - Optional optional1 = ops.getNumberValue(value).result(); - return optional1.isPresent() ? optional1.get().doubleValue() != 0.0 : null; + Optional asNumber = ops.getNumberValue(arg).result(); + return asNumber.isPresent() ? asNumber.get().doubleValue() != 0.0 : null; } } }, new BuiltinKey("uuid", 1), new BuiltinOperation() { @Override - public T run(DynamicOps ops, List args, ParseState parseState) { - Optional optional = ops.getStringValue(args.getFirst()).result(); - if (optional.isEmpty()) { - parseState.errorCollector().store(parseState.mark(), SnbtOperations.ERROR_EXPECTED_STRING_UUID); + public T run(DynamicOps ops, List arguments, ParseState state) { + Optional arg = ops.getStringValue(arguments.getFirst()).result(); + if (arg.isEmpty()) { + state.errorCollector().store(state.mark(), SnbtOperations.ERROR_EXPECTED_STRING_UUID); return null; - } else { - UUID uuid; - try { - uuid = UUID.fromString(optional.get()); - } catch (IllegalArgumentException var7) { - parseState.errorCollector().store(parseState.mark(), SnbtOperations.ERROR_EXPECTED_STRING_UUID); - return null; - } - - return ops.createIntList(IntStream.of(UUIDUtil.uuidToIntArray(uuid))); } + UUID uuid; + try { + uuid = UUID.fromString(arg.get()); + } catch (IllegalArgumentException var7) { + state.errorCollector().store(state.mark(), SnbtOperations.ERROR_EXPECTED_STRING_UUID); + return null; + } + + return ops.createIntList(IntStream.of(UUIDUtil.uuidToIntArray(uuid))); } } ); @@ -74,7 +72,7 @@ public class SnbtOperations { .collect(Collectors.toSet()); @Override - public Stream possibleValues(ParseState parseState) { + public Stream possibleValues(ParseState state) { return this.keys.stream(); } }; @@ -88,6 +86,6 @@ public class SnbtOperations { public interface BuiltinOperation { @Nullable - T run(DynamicOps ops, List args, ParseState parseState); + T run(DynamicOps ops, List arguments, ParseState state); } } diff --git a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/TagParser.java b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/TagParser.java index 6c7badbf9..d399e6151 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/TagParser.java +++ b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/TagParser.java @@ -42,34 +42,34 @@ public class TagParser { return new TagParser<>(ops, SnbtGrammar.createParser(ops)); } - private static CompoundTag castToCompoundOrThrow(StringReader reader, Tag tag) throws CommandSyntaxException { - if (tag instanceof CompoundTag compoundTag) { + private static CompoundTag castToCompoundOrThrow(StringReader reader, Tag result) throws CommandSyntaxException { + if (result instanceof CompoundTag compoundTag) { return compoundTag; } throw ERROR_EXPECTED_COMPOUND.createWithContext(reader); } - public static CompoundTag parseCompoundFully(String data) throws CommandSyntaxException { - StringReader stringReader = new StringReader(data); - return parseCompoundAsArgument(stringReader); + public static CompoundTag parseCompoundFully(String input) throws CommandSyntaxException { + StringReader reader = new StringReader(input); + return parseCompoundAsArgument(reader); } - public static Object parseObjectFully(String data) throws CommandSyntaxException { - StringReader stringReader = new StringReader(data); - return parseObjectAsArgument(stringReader); + public static Object parseObjectFully(String input) throws CommandSyntaxException { + StringReader reader = new StringReader(input); + return parseObjectAsArgument(reader); } - public T parseFully(String text) throws CommandSyntaxException { - return this.parseFully(new StringReader(text)); + public T parseFully(String input) throws CommandSyntaxException { + return this.parseFully(new StringReader(input)); } public T parseFully(StringReader reader) throws CommandSyntaxException { - T object = this.grammar.parse(reader); + T result = this.grammar.parse(reader); reader.skipWhitespace(); if (reader.canRead()) { throw ERROR_TRAILING_DATA.createWithContext(reader); } - return object; + return result; } public T parseAsArgument(StringReader reader) throws CommandSyntaxException { diff --git a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/CachedParseState.java b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/CachedParseState.java index 03c439c82..b71d66c24 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/CachedParseState.java +++ b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/CachedParseState.java @@ -1,7 +1,5 @@ package net.momirealms.craftengine.core.util.snbt.parse; -import it.unimi.dsi.fastutil.ints.IntArrayList; -import it.unimi.dsi.fastutil.ints.IntList; import net.momirealms.craftengine.core.util.MiscUtils; import javax.annotation.Nullable; @@ -14,7 +12,6 @@ public abstract class CachedParseState implements ParseState { private SimpleControl[] controlCache = new SimpleControl[16]; private int nextControlToReturn; private final Silent silent = new Silent(); - private final IntList markedNull = new IntArrayList(); public static final Object JAVA_NULL_VALUE_MARKER = new Object() { @Override public String toString() { @@ -39,11 +36,11 @@ public abstract class CachedParseState implements ParseState { @Nullable @Override public T parse(NamedRule rule) { - int i = this.mark(); - PositionCache cacheForPosition = this.getCacheForPosition(i); - int i1 = cacheForPosition.findKeyIndex(rule.name()); - if (i1 != -1) { - CacheEntry value = cacheForPosition.getValue(i1); + int markBeforeParse = this.mark(); + PositionCache positionCache = this.getCacheForPosition(markBeforeParse); + int entryIndex = positionCache.findKeyIndex(rule.name()); + if (entryIndex != -1) { + CacheEntry value = positionCache.getValue(entryIndex); if (value != null) { if (value == CachedParseState.CacheEntry.NEGATIVE) { return null; @@ -52,59 +49,60 @@ public abstract class CachedParseState implements ParseState { return value.value; } } else { - i1 = cacheForPosition.allocateNewEntry(rule.name()); + entryIndex = positionCache.allocateNewEntry(rule.name()); } - T object = rule.value().parse(this); - CacheEntry cacheEntry; - if (object == null) { - cacheEntry = (CacheEntry) CacheEntry.NEGATIVE; + T result = rule.value().parse(this); + CacheEntry entry; + if (result == null) { + entry = CacheEntry.negativeEntry(); } else { - cacheEntry = new CacheEntry<>(object, this.mark()); + int markAfterParse = this.mark(); + entry = new CacheEntry<>(result, markAfterParse); } - cacheForPosition.setValue(i1, cacheEntry); - return object; + positionCache.setValue(entryIndex, entry); + return result; } - private PositionCache getCacheForPosition(int position) { - int i = this.positionCache.length; - if (position >= i) { - int i1 = MiscUtils.growByHalf(i, position + 1); - PositionCache[] positionCaches = new PositionCache[i1]; - System.arraycopy(this.positionCache, 0, positionCaches, 0, i); - this.positionCache = positionCaches; + private PositionCache getCacheForPosition(int index) { + int currentSize = this.positionCache.length; + if (index >= currentSize) { + int newSize = MiscUtils.growByHalf(currentSize, index + 1); + PositionCache[] newCache = new PositionCache[newSize]; + System.arraycopy(this.positionCache, 0, newCache, 0, currentSize); + this.positionCache = newCache; } - PositionCache positionCache = this.positionCache[position]; - if (positionCache == null) { - positionCache = new PositionCache(); - this.positionCache[position] = positionCache; + PositionCache result = this.positionCache[index]; + if (result == null) { + result = new PositionCache(); + this.positionCache[index] = result; } - return positionCache; + return result; } @Override public Control acquireControl() { - int i = this.controlCache.length; - if (this.nextControlToReturn >= i) { - int i1 = MiscUtils.growByHalf(i, this.nextControlToReturn + 1); - SimpleControl[] simpleControls = new SimpleControl[i1]; - System.arraycopy(this.controlCache, 0, simpleControls, 0, i); - this.controlCache = simpleControls; + int currentSize = this.controlCache.length; + if (this.nextControlToReturn >= currentSize) { + int newSize = MiscUtils.growByHalf(currentSize, this.nextControlToReturn + 1); + SimpleControl[] newControlCache = new SimpleControl[newSize]; + System.arraycopy(this.controlCache, 0, newControlCache, 0, currentSize); + this.controlCache = newControlCache; } - int i1 = this.nextControlToReturn++; - SimpleControl simpleControl = this.controlCache[i1]; - if (simpleControl == null) { - simpleControl = new SimpleControl(); - this.controlCache[i1] = simpleControl; + int controlIndex = this.nextControlToReturn++; + SimpleControl entry = this.controlCache[controlIndex]; + if (entry == null) { + entry = new SimpleControl(); + this.controlCache[controlIndex] = entry; } else { - simpleControl.reset(); + entry.reset(); } - return simpleControl; + return entry; } @Override @@ -117,18 +115,12 @@ public abstract class CachedParseState implements ParseState { return this.silent; } - @Override - public void markNull(int mark) { - this.markedNull.add(mark); - } - - @Override - public boolean isNull(int mark) { - return this.markedNull.contains(mark); - } - record CacheEntry(@Nullable T value, int markAfterParse) { public static final CacheEntry NEGATIVE = new CacheEntry<>(null, -1); + + public static CacheEntry negativeEntry() { + return (CacheEntry) NEGATIVE; + } } static class PositionCache { @@ -137,9 +129,9 @@ public abstract class CachedParseState implements ParseState { private Object[] atomCache = new Object[16]; private int nextKey; - public int findKeyIndex(Atom atom) { + public int findKeyIndex(Atom key) { for (int i = 0; i < this.nextKey; i += ENTRY_STRIDE) { - if (this.atomCache[i] == atom) { + if (this.atomCache[i] == key) { return i; } } @@ -147,29 +139,29 @@ public abstract class CachedParseState implements ParseState { return NOT_FOUND; } - public int allocateNewEntry(Atom entry) { - int i = this.nextKey; - this.nextKey += 2; - int i1 = i + 1; - int i2 = this.atomCache.length; - if (i1 >= i2) { - int i3 = MiscUtils.growByHalf(i2, i1 + 1); - Object[] objects = new Object[i3]; - System.arraycopy(this.atomCache, 0, objects, 0, i2); - this.atomCache = objects; + public int allocateNewEntry(Atom key) { + int newKeyIndex = this.nextKey; + this.nextKey += ENTRY_STRIDE; + int newValueIndex = newKeyIndex + 1; + int currentSize = this.atomCache.length; + if (newValueIndex >= currentSize) { + int newSize = MiscUtils.growByHalf(currentSize, newValueIndex + 1); + Object[] newCache = new Object[newSize]; + System.arraycopy(this.atomCache, 0, newCache, 0, currentSize); + this.atomCache = newCache; } - this.atomCache[i] = entry; - return i; + this.atomCache[newKeyIndex] = key; + return newKeyIndex; } @Nullable - public CacheEntry getValue(int index) { - return (CacheEntry)this.atomCache[index + 1]; + public CacheEntry getValue(int keyIndex) { + return (CacheEntry) this.atomCache[keyIndex + 1]; } - public void setValue(int index, CacheEntry value) { - this.atomCache[index + 1] = value; + public void setValue(int keyIndex, CacheEntry entry) { + this.atomCache[keyIndex + 1] = entry; } } @@ -203,8 +195,8 @@ public abstract class CachedParseState implements ParseState { } @Override - public void restore(int cursor) { - CachedParseState.this.restore(cursor); + public void restore(int mark) { + CachedParseState.this.restore(mark); } @Override @@ -221,16 +213,6 @@ public abstract class CachedParseState implements ParseState { public ParseState silent() { return this; } - - @Override - public void markNull(int mark) { - CachedParseState.this.markNull(mark); - } - - @Override - public boolean isNull(int mark) { - return CachedParseState.this.isNull(mark); - } } static class SimpleControl implements Control { diff --git a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/DelayedException.java b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/DelayedException.java index ee79b450c..173b85840 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/DelayedException.java +++ b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/DelayedException.java @@ -7,13 +7,13 @@ import net.momirealms.craftengine.core.util.snbt.parse.grammar.StringReaderTerms @FunctionalInterface public interface DelayedException { - T create(String message, int cursor); + T create(String contents, int position); - static DelayedException create(SimpleCommandExceptionType exception) { - return (message, cursor) -> exception.createWithContext(StringReaderTerms.createReader(message, cursor)); + static DelayedException create(SimpleCommandExceptionType type) { + return (contents, position) -> type.createWithContext(StringReaderTerms.createReader(contents, position)); } - static DelayedException create(DynamicCommandExceptionType exception, String argument) { - return (message, cursor) -> exception.createWithContext(StringReaderTerms.createReader(message, cursor), argument); + static DelayedException create(DynamicCommandExceptionType type, String argument) { + return (contents, position) -> type.createWithContext(StringReaderTerms.createReader(contents, position), argument); } } diff --git a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/Dictionary.java b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/Dictionary.java index 20d6c4bb2..66ea4e088 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/Dictionary.java +++ b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/Dictionary.java @@ -11,28 +11,30 @@ import java.util.function.Supplier; public class Dictionary { private final Map, Entry> terms = new IdentityHashMap<>(); - public NamedRule put(Atom name, Rule rule) { - Entry entry = (Entry)this.terms.computeIfAbsent(name, Entry::new); - if (entry.value != null) { + public NamedRule put(Atom name, Rule entry) { + Entry holder = (Entry)this.terms.computeIfAbsent(name, Entry::new); + if (holder.value != null) { throw new IllegalArgumentException("Trying to override rule: " + name); - } else { - entry.value = rule; - return entry; } + holder.value = entry; + return holder; } - public NamedRule putComplex(Atom name, Term term, Rule.RuleAction ruleAction) { - return this.put(name, Rule.fromTerm(term, ruleAction)); + public NamedRule putComplex(Atom name, Term term, Rule.RuleAction action) { + return this.put(name, Rule.fromTerm(term, action)); } - public NamedRule put(Atom name, Term term, Rule.SimpleRuleAction ruleAction) { - return this.put(name, Rule.fromTerm(term, ruleAction)); + public NamedRule put(Atom name, Term term, Rule.SimpleRuleAction action) { + return this.put(name, Rule.fromTerm(term, action)); } public void checkAllBound() { - List> list = this.terms.entrySet().stream().filter(entry -> entry.getValue() == null).map(Map.Entry::getKey).toList(); - if (!list.isEmpty()) { - throw new IllegalStateException("Unbound names: " + list); + List> unboundNames = this.terms.entrySet().stream() + .filter(entry -> entry.getValue() == null) + .map(Map.Entry::getKey) + .toList(); + if (!unboundNames.isEmpty()) { + throw new IllegalStateException("Unbound names: " + unboundNames); } } @@ -48,8 +50,8 @@ public class Dictionary { return new Reference<>(this.getOrCreateEntry(name), name); } - public Term namedWithAlias(Atom name, Atom alias) { - return new Reference<>(this.getOrCreateEntry(name), alias); + public Term namedWithAlias(Atom nameToParse, Atom nameToStore) { + return new Reference<>(this.getOrCreateEntry(nameToParse), nameToStore); } static class Entry implements NamedRule, Supplier { @@ -79,14 +81,13 @@ public class Dictionary { record Reference(Entry ruleToParse, Atom nameToStore) implements Term { @Override - public boolean parse(ParseState parseState, Scope scope, Control control) { - T object = parseState.parse(this.ruleToParse); - if (object == null) { + public boolean parse(ParseState state, Scope scope, Control control) { + T result = state.parse(this.ruleToParse); + if (result == null) { return false; - } else { - scope.put(this.nameToStore, object); - return true; } + scope.put(this.nameToStore, result); + return true; } } } diff --git a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/ErrorCollector.java b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/ErrorCollector.java index ef0aac7e3..1bb43a0ae 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/ErrorCollector.java +++ b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/ErrorCollector.java @@ -13,7 +13,7 @@ public interface ErrorCollector { this.store(cursor, SuggestionSupplier.empty(), reason); } - void finish(int cursor); + void finish(int finalCursor); class LongestOnly implements ErrorCollector { private MutableErrorEntry[] entries = new MutableErrorEntry[16]; @@ -28,8 +28,8 @@ public interface ErrorCollector { } @Override - public void finish(int cursor) { - this.discardErrorsFromShorterParse(cursor); + public void finish(int finalCursor) { + this.discardErrorsFromShorterParse(finalCursor); } @Override @@ -41,39 +41,38 @@ public interface ErrorCollector { } private void addErrorEntry(SuggestionSupplier suggestions, Object reason) { - int i = this.entries.length; - if (this.nextErrorEntry >= i) { - int i1 = MiscUtils.growByHalf(i, this.nextErrorEntry + 1); - MutableErrorEntry[] mutableErrorEntrys = new MutableErrorEntry[i1]; - System.arraycopy(this.entries, 0, mutableErrorEntrys, 0, i); - this.entries = mutableErrorEntrys; + int currentSize = this.entries.length; + if (this.nextErrorEntry >= currentSize) { + int newSize = MiscUtils.growByHalf(currentSize, this.nextErrorEntry + 1); + MutableErrorEntry[] newEntries = new MutableErrorEntry[newSize]; + System.arraycopy(this.entries, 0, newEntries, 0, currentSize); + this.entries = newEntries; } - int i1 = this.nextErrorEntry++; - MutableErrorEntry mutableErrorEntry = this.entries[i1]; - if (mutableErrorEntry == null) { - mutableErrorEntry = new MutableErrorEntry<>(); - this.entries[i1] = mutableErrorEntry; + int entryIndex = this.nextErrorEntry++; + MutableErrorEntry entry = this.entries[entryIndex]; + if (entry == null) { + entry = new MutableErrorEntry<>(); + this.entries[entryIndex] = entry; } - mutableErrorEntry.suggestions = suggestions; - mutableErrorEntry.reason = reason; + entry.suggestions = suggestions; + entry.reason = reason; } public List> entries() { - int i = this.nextErrorEntry; - if (i == 0) { + int errorCount = this.nextErrorEntry; + if (errorCount == 0) { return List.of(); - } else { - List> list = new ArrayList<>(i); - - for (int i1 = 0; i1 < i; i1++) { - MutableErrorEntry mutableErrorEntry = this.entries[i1]; - list.add(new ErrorEntry<>(this.lastCursor, mutableErrorEntry.suggestions, mutableErrorEntry.reason)); - } - - return list; } + List> result = new ArrayList<>(errorCount); + + for (int i = 0; i < errorCount; i++) { + MutableErrorEntry mutableErrorEntry = this.entries[i]; + result.add(new ErrorEntry<>(this.lastCursor, mutableErrorEntry.suggestions, mutableErrorEntry.reason)); + } + + return result; } public int cursor() { @@ -92,7 +91,7 @@ public interface ErrorCollector { } @Override - public void finish(int cursor) { + public void finish(int finalCursor) { } } } diff --git a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/ParseState.java b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/ParseState.java index 5a631476b..2ab971364 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/ParseState.java +++ b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/ParseState.java @@ -9,16 +9,15 @@ public interface ParseState { ErrorCollector errorCollector(); default Optional parseTopRule(NamedRule rule) { - T object = this.parse(rule); - if (object != null) { + T result = this.parse(rule); + if (result != null) { this.errorCollector().finish(this.mark()); } if (!this.scope().hasOnlySingleFrame()) { throw new IllegalStateException("Malformed scope: " + this.scope()); - } else { - return Optional.ofNullable(object); } + return Optional.ofNullable(result); } @Nullable @@ -28,15 +27,11 @@ public interface ParseState { int mark(); - void restore(int cursor); + void restore(int mark); Control acquireControl(); void releaseControl(); ParseState silent(); - - void markNull(int mark); - - boolean isNull(int mark); } diff --git a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/Rule.java b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/Rule.java index 6a5728ec4..cfb7403c4 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/Rule.java +++ b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/Rule.java @@ -4,7 +4,7 @@ import javax.annotation.Nullable; public interface Rule { @Nullable - T parse(ParseState parseState); + T parse(ParseState state); static Rule fromTerm(Term child, RuleAction action) { return new WrappedTerm<>(action, child); @@ -17,38 +17,35 @@ public interface Rule { @FunctionalInterface interface RuleAction { @Nullable - T run(ParseState parseState); + T run(ParseState state); } @FunctionalInterface interface SimpleRuleAction extends RuleAction { - T run(Scope scope); + T run(Scope ruleScope); @Override - default T run(ParseState parseState) { - return this.run(parseState.scope()); + default T run(ParseState state) { + return this.run(state.scope()); } } record WrappedTerm(RuleAction action, Term child) implements Rule { @Nullable @Override - public T parse(ParseState parseState) { - Scope scope = parseState.scope(); + public T parse(ParseState state) { + Scope scope = state.scope(); scope.pushFrame(); - T var3; try { - if (!this.child.parse(parseState, scope, Control.UNBOUND)) { + if (!this.child.parse(state, scope, Control.UNBOUND)) { return null; } - var3 = this.action.run(parseState); + return this.action.run(state); } finally { scope.popFrame(); } - - return var3; } } } diff --git a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/Scope.java b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/Scope.java index 81ad7ecfd..d152ecc89 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/Scope.java +++ b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/Scope.java @@ -28,13 +28,13 @@ public final class Scope { this.stack[1] = null; } - private int valueIndex(Atom name) { + private int valueIndex(Atom atom) { for (int i = this.topEntryKeyIndex; i > this.topMarkerKeyIndex; i -= ENTRY_STRIDE) { - Object object = this.stack[i]; + Object key = this.stack[i]; - assert object instanceof Atom; + assert key instanceof Atom; - if (object == name) { + if (key == atom) { return i + 1; } } @@ -42,14 +42,14 @@ public final class Scope { return NOT_FOUND; } - public int valueIndexForAny(Atom... names) { + public int valueIndexForAny(Atom... atoms) { for (int i = this.topEntryKeyIndex; i > this.topMarkerKeyIndex; i -= ENTRY_STRIDE) { - Object object = this.stack[i]; + Object key = this.stack[i]; - assert object instanceof Atom; + assert key instanceof Atom; - for (Atom atom : names) { - if (atom == object) { + for (Atom atom : atoms) { + if (atom == key) { return i + 1; } } @@ -58,15 +58,15 @@ public final class Scope { return NOT_FOUND; } - private void ensureCapacity(int requiredCapacitty) { - int i = this.stack.length; - int i1 = this.topEntryKeyIndex + 1; - int i2 = i1 + requiredCapacitty * 2; - if (i2 >= i) { - int i3 = MiscUtils.growByHalf(i, i2 + 1); - Object[] objects = new Object[i3]; - System.arraycopy(this.stack, 0, objects, 0, i); - this.stack = objects; + private void ensureCapacity(int additionalEntryCount) { + int currentSize = this.stack.length; + int currentLastValueIndex = this.topEntryKeyIndex + 1; + int newLastValueIndex = currentLastValueIndex + additionalEntryCount * 2; + if (newLastValueIndex >= currentSize) { + int newSize = MiscUtils.growByHalf(currentSize, newLastValueIndex + 1); + Object[] newStack = new Object[newSize]; + System.arraycopy(this.stack, 0, newStack, 0, currentSize); + this.stack = newStack; } assert this.validateStructure(); @@ -86,8 +86,8 @@ public final class Scope { assert this.validateStructure(); } - private int getPreviousMarkerIndex(int markerIndex) { - return (Integer)this.stack[markerIndex + 1]; + private int getPreviousMarkerIndex(int markerKeyIndex) { + return (Integer) this.stack[markerKeyIndex + 1]; } public void popFrame() { @@ -100,25 +100,25 @@ public final class Scope { } public void splitFrame() { - int i = this.topMarkerKeyIndex; - int i1 = (this.topEntryKeyIndex - this.topMarkerKeyIndex) / ENTRY_STRIDE; - this.ensureCapacity(i1 + 1); + int currentFrameMarkerIndex = this.topMarkerKeyIndex; + int nonMarkerEntriesInFrame = (this.topEntryKeyIndex - this.topMarkerKeyIndex) / ENTRY_STRIDE; + this.ensureCapacity(nonMarkerEntriesInFrame + 1); this.setupNewFrame(); - int i2 = i + ENTRY_STRIDE; - int i3 = this.topEntryKeyIndex; + int sourceCursor = currentFrameMarkerIndex + ENTRY_STRIDE; + int targetCursor = this.topEntryKeyIndex; - for (int i4 = 0; i4 < i1; i4++) { - i3 += ENTRY_STRIDE; - Object object = this.stack[i2]; + for (int i = 0; i < nonMarkerEntriesInFrame; i++) { + targetCursor += ENTRY_STRIDE; + Object key = this.stack[sourceCursor]; - assert object != null; + assert key != null; - this.stack[i3] = object; - this.stack[i3 + 1] = null; - i2 += ENTRY_STRIDE; + this.stack[targetCursor] = key; + this.stack[targetCursor + 1] = null; + sourceCursor += ENTRY_STRIDE; } - this.topEntryKeyIndex = i3; + this.topEntryKeyIndex = targetCursor; assert this.validateStructure(); } @@ -135,40 +135,40 @@ public final class Scope { public void mergeFrame() { int previousMarkerIndex = this.getPreviousMarkerIndex(this.topMarkerKeyIndex); - int i = previousMarkerIndex; - int i1 = this.topMarkerKeyIndex; + int previousFrameCursor = previousMarkerIndex; + int currentFrameCursor = this.topMarkerKeyIndex; - while (i1 < this.topEntryKeyIndex) { - i += ENTRY_STRIDE; - i1 += ENTRY_STRIDE; - Object object = this.stack[i1]; + while (currentFrameCursor < this.topEntryKeyIndex) { + previousFrameCursor += ENTRY_STRIDE; + currentFrameCursor += ENTRY_STRIDE; + Object newKey = this.stack[currentFrameCursor]; - assert object instanceof Atom; + assert newKey instanceof Atom; - Object object1 = this.stack[i1 + 1]; - Object object2 = this.stack[i]; - if (object2 != object) { - this.stack[i] = object; - this.stack[i + 1] = object1; - } else if (object1 != null) { - this.stack[i + 1] = object1; + Object newValue = this.stack[currentFrameCursor + 1]; + Object oldKey = this.stack[previousFrameCursor]; + if (oldKey != newKey) { + this.stack[previousFrameCursor] = newKey; + this.stack[previousFrameCursor + 1] = newValue; + } else if (newValue != null) { + this.stack[previousFrameCursor + 1] = newValue; } } - this.topEntryKeyIndex = i; + this.topEntryKeyIndex = previousFrameCursor; this.topMarkerKeyIndex = previousMarkerIndex; assert this.validateStructure(); } - public void put(Atom atom, @Nullable T value) { - int i = this.valueIndex(atom); - if (i != NOT_FOUND) { - this.stack[i] = value; + public void put(Atom name, @Nullable T value) { + int valueIndex = this.valueIndex(name); + if (valueIndex != NOT_FOUND) { + this.stack[valueIndex] = value; } else { this.ensureCapacity(1); this.topEntryKeyIndex += ENTRY_STRIDE; - this.stack[this.topEntryKeyIndex] = atom; + this.stack[this.topEntryKeyIndex] = name; this.stack[this.topEntryKeyIndex + 1] = value; } @@ -176,77 +176,75 @@ public final class Scope { } @Nullable - public T get(Atom atom) { - int i = this.valueIndex(atom); - return (T)(i != NOT_FOUND ? this.stack[i] : null); + public T get(Atom name) { + int valueIndex = this.valueIndex(name); + return (T) (valueIndex != NOT_FOUND ? this.stack[valueIndex] : null); } - public T getOrThrow(Atom atom) { - int i = this.valueIndex(atom); - if (i == NOT_FOUND) { - throw new IllegalArgumentException("No value for atom " + atom); - } else { - return (T)this.stack[i]; + public T getOrThrow(Atom name) { + int valueIndex = this.valueIndex(name); + if (valueIndex == NOT_FOUND) { + throw new IllegalArgumentException("No value for atom " + name); } + return (T) this.stack[valueIndex]; } - public T getOrDefault(Atom atom, T defaultValue) { - int i = this.valueIndex(atom); - return (T)(i != NOT_FOUND ? this.stack[i] : defaultValue); + public T getOrDefault(Atom name, T fallback) { + int valueIndex = this.valueIndex(name); + return (T) (valueIndex != NOT_FOUND ? this.stack[valueIndex] : fallback); } @Nullable @SafeVarargs - public final T getAny(Atom... atoms) { - int i = this.valueIndexForAny(atoms); - return (T)(i != NOT_FOUND ? this.stack[i] : null); + public final T getAny(Atom... names) { + int valueIndex = this.valueIndexForAny(names); + return (T) (valueIndex != NOT_FOUND ? this.stack[valueIndex] : null); } @SafeVarargs - public final T getAnyOrThrow(Atom... atoms) { - int i = this.valueIndexForAny(atoms); - if (i == NOT_FOUND) { - throw new IllegalArgumentException("No value for atoms " + Arrays.toString(atoms)); - } else { - return (T)this.stack[i]; + public final T getAnyOrThrow(Atom... names) { + int valueIndex = this.valueIndexForAny(names); + if (valueIndex == NOT_FOUND) { + throw new IllegalArgumentException("No value for atoms " + Arrays.toString(names)); } + return (T) this.stack[valueIndex]; } @Override public String toString() { - StringBuilder stringBuilder = new StringBuilder(); - boolean flag = true; + StringBuilder result = new StringBuilder(); + boolean afterFrame = true; for (int i = 0; i <= this.topEntryKeyIndex; i += ENTRY_STRIDE) { - Object object = this.stack[i]; - Object object1 = this.stack[i + 1]; - if (object == FRAME_START_MARKER) { - stringBuilder.append('|'); - flag = true; + Object key = this.stack[i]; + Object value = this.stack[i + 1]; + if (key == FRAME_START_MARKER) { + result.append('|'); + afterFrame = true; } else { - if (!flag) { - stringBuilder.append(','); + if (!afterFrame) { + result.append(','); } - flag = false; - stringBuilder.append(object).append(':').append(object1); + afterFrame = false; + result.append(key).append(':').append(value); } } - return stringBuilder.toString(); + return result.toString(); } @VisibleForTesting public Map, ?> lastFrame() { - HashMap, Object> map = new HashMap<>(); + HashMap, Object> result = new HashMap<>(); for (int i = this.topEntryKeyIndex; i > this.topMarkerKeyIndex; i -= ENTRY_STRIDE) { - Object object = this.stack[i]; - Object object1 = this.stack[i + 1]; - map.put((Atom)object, object1); + Object key = this.stack[i]; + Object value = this.stack[i + 1]; + result.put((Atom) key, value); } - return map; + return result; } public boolean hasOnlySingleFrame() { @@ -258,9 +256,8 @@ public final class Scope { if (this.stack[0] != FRAME_START_MARKER) { throw new IllegalStateException("Corrupted stack"); - } else { - return true; } + return true; } private boolean validateStructure() { @@ -285,14 +282,15 @@ public final class Scope { return true; } - @SuppressWarnings({"unchecked","rawtypes"}) + @SuppressWarnings({"unchecked", "rawtypes"}) public static Term increaseDepth() { class IncreasingDepthTerm implements Term { public static final IncreasingDepthTerm INSTANCE = new IncreasingDepthTerm(); + @Override - public boolean parse(final ParseState parseState, final Scope scope, final Control control) { + public boolean parse(final ParseState state, final Scope scope, final Control control) { if (++scope.depth > 512) { - parseState.errorCollector().store(parseState.mark(), new IllegalStateException("Too deep")); + state.errorCollector().store(state.mark(), new IllegalStateException("Too deep")); return false; } return true; @@ -301,12 +299,13 @@ public final class Scope { return (Term) IncreasingDepthTerm.INSTANCE; } - @SuppressWarnings({"unchecked","rawtypes"}) + @SuppressWarnings({"unchecked", "rawtypes"}) public static Term decreaseDepth() { class DecreasingDepthTerm implements Term { public static final DecreasingDepthTerm INSTANCE = new DecreasingDepthTerm(); + @Override - public boolean parse(final ParseState parseState, final Scope scope, final Control control) { + public boolean parse(final ParseState state, final Scope scope, final Control control) { scope.depth--; return true; } diff --git a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/SuggestionSupplier.java b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/SuggestionSupplier.java index ed88ccd42..30c32ac7c 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/SuggestionSupplier.java +++ b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/SuggestionSupplier.java @@ -3,9 +3,9 @@ package net.momirealms.craftengine.core.util.snbt.parse; import java.util.stream.Stream; public interface SuggestionSupplier { - Stream possibleValues(ParseState parseState); + Stream possibleValues(ParseState state); static SuggestionSupplier empty() { - return parseState -> Stream.empty(); + return state -> Stream.empty(); } } diff --git a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/Term.java b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/Term.java index ceab78ef0..383602b0e 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/Term.java +++ b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/Term.java @@ -4,20 +4,20 @@ import java.util.ArrayList; import java.util.List; public interface Term { - boolean parse(ParseState parseState, Scope scope, Control control); + boolean parse(ParseState state, Scope scope, Control control); static Term marker(Atom name, T value) { return new Marker<>(name, value); } @SafeVarargs - static Term sequence(Term... elements) { - return new Sequence<>(elements); + static Term sequence(Term... terms) { + return new Sequence<>(terms); } @SafeVarargs - static Term alternative(Term... elements) { - return new Alternative<>(elements); + static Term alternative(Term... terms) { + return new Alternative<>(terms); } static Term optional(Term term) { @@ -32,8 +32,8 @@ public interface Term { return new Repeated<>(element, listName, minRepetitions); } - static Term repeatedWithTrailingSeparator(NamedRule element, Atom> listName, Term seperator) { - return repeatedWithTrailingSeparator(element, listName, seperator, 0); + static Term repeatedWithTrailingSeparator(NamedRule element, Atom> listName, Term separator) { + return repeatedWithTrailingSeparator(element, listName, separator, 0); } static Term repeatedWithTrailingSeparator(NamedRule element, Atom> listName, Term seperator, int minRepetitions) { @@ -47,7 +47,7 @@ public interface Term { static Term cut() { return new Term<>() { @Override - public boolean parse(ParseState parseState, Scope scope, Control control) { + public boolean parse(ParseState state, Scope scope, Control control) { control.cut(); return true; } @@ -62,7 +62,7 @@ public interface Term { static Term empty() { return new Term<>() { @Override - public boolean parse(ParseState parseState, Scope scope, Control control) { + public boolean parse(ParseState state, Scope scope, Control control) { return true; } @@ -73,11 +73,11 @@ public interface Term { }; } - static Term fail(final Object reason) { + static Term fail(final Object message) { return new Term<>() { @Override - public boolean parse(ParseState parseState, Scope scope, Control control) { - parseState.errorCollector().store(parseState.mark(), reason); + public boolean parse(ParseState state, Scope scope, Control control) { + state.errorCollector().store(state.mark(), message); return false; } @@ -90,22 +90,22 @@ public interface Term { record Alternative(Term[] elements) implements Term { @Override - public boolean parse(ParseState parseState, Scope scope, Control control) { - Control control1 = parseState.acquireControl(); + public boolean parse(ParseState state, Scope scope, Control control) { + Control controlForThis = state.acquireControl(); try { - int i = parseState.mark(); + int mark = state.mark(); scope.splitFrame(); - for (Term term : this.elements) { - if (term.parse(parseState, scope, control1)) { + for (Term element : this.elements) { + if (element.parse(state, scope, controlForThis)) { scope.mergeFrame(); return true; } scope.clearFrameValues(); - parseState.restore(i); - if (control1.hasCut()) { + state.restore(mark); + if (controlForThis.hasCut()) { break; } } @@ -113,24 +113,24 @@ public interface Term { scope.popFrame(); return false; } finally { - parseState.releaseControl(); + state.releaseControl(); } } } record LookAhead(Term term, boolean positive) implements Term { @Override - public boolean parse(ParseState parseState, Scope scope, Control control) { - int i = parseState.mark(); - boolean flag = this.term.parse(parseState.silent(), scope, control); - parseState.restore(i); - return this.positive == flag; + public boolean parse(ParseState state, Scope scope, Control control) { + int mark = state.mark(); + boolean result = this.term.parse(state.silent(), scope, control); + state.restore(mark); + return this.positive == result; } } record Marker(Atom name, T value) implements Term { @Override - public boolean parse(ParseState parseState, Scope scope, Control control) { + public boolean parse(ParseState state, Scope scope, Control control) { scope.put(this.name, this.value); return true; } @@ -138,10 +138,10 @@ public interface Term { record Maybe(Term term) implements Term { @Override - public boolean parse(ParseState parseState, Scope scope, Control control) { - int i = parseState.mark(); - if (!this.term.parse(parseState, scope, control)) { - parseState.restore(i); + public boolean parse(ParseState state, Scope scope, Control control) { + int mark = state.mark(); + if (!this.term.parse(state, scope, control)) { + state.restore(mark); } return true; @@ -150,25 +150,24 @@ public interface Term { record Repeated(NamedRule element, Atom> listName, int minRepetitions) implements Term { @Override - public boolean parse(ParseState parseState, Scope scope, Control control) { - int i = parseState.mark(); - List list = new ArrayList<>(this.minRepetitions); + public boolean parse(ParseState state, Scope scope, Control control) { + int mark = state.mark(); + List elements = new ArrayList<>(this.minRepetitions); while (true) { - int i1 = parseState.mark(); - T object = parseState.parse(this.element); - if (object == null) { - parseState.restore(i1); - if (list.size() < this.minRepetitions) { - parseState.restore(i); + int entryMark = state.mark(); + T parsedElement = state.parse(this.element); + if (parsedElement == null) { + state.restore(entryMark); + if (elements.size() < this.minRepetitions) { + state.restore(mark); return false; - } else { - scope.put(this.listName, list); - return true; } + scope.put(this.listName, elements); + return true; } - list.add(object); + elements.add(parsedElement); } } } @@ -177,56 +176,55 @@ public interface Term { NamedRule element, Atom> listName, Term separator, int minRepetitions, boolean allowTrailingSeparator ) implements Term { @Override - public boolean parse(ParseState parseState, Scope scope, Control control) { - int i = parseState.mark(); - List list = new ArrayList<>(this.minRepetitions); - boolean flag = true; + public boolean parse(ParseState state, Scope scope, Control control) { + int listMark = state.mark(); + List elements = new ArrayList<>(this.minRepetitions); + boolean first = true; while (true) { - int i1 = parseState.mark(); - if (!flag && !this.separator.parse(parseState, scope, control)) { - parseState.restore(i1); + int markBeforeSeparator = state.mark(); + if (!first && !this.separator.parse(state, scope, control)) { + state.restore(markBeforeSeparator); break; } - int i2 = parseState.mark(); - T object = parseState.parse(this.element); - if (object == null) { - if (flag) { - parseState.restore(i2); + int markAfterSeparator = state.mark(); + T parsedElement = state.parse(this.element); + if (parsedElement == null) { + if (first) { + state.restore(markAfterSeparator); } else { if (!this.allowTrailingSeparator) { - parseState.restore(i); + state.restore(listMark); return false; } - parseState.restore(i2); + state.restore(markAfterSeparator); } break; } - list.add(object); - flag = false; + elements.add(parsedElement); + first = false; } - if (list.size() < this.minRepetitions) { - parseState.restore(i); + if (elements.size() < this.minRepetitions) { + state.restore(listMark); return false; - } else { - scope.put(this.listName, list); - return true; } + scope.put(this.listName, elements); + return true; } } record Sequence(Term[] elements) implements Term { @Override - public boolean parse(ParseState parseState, Scope scope, Control control) { - int i = parseState.mark(); + public boolean parse(ParseState state, Scope scope, Control control) { + int mark = state.mark(); - for (Term term : this.elements) { - if (!term.parse(parseState, scope, control)) { - parseState.restore(i); + for (Term element : this.elements) { + if (!element.parse(state, scope, control)) { + state.restore(mark); return false; } } diff --git a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/Grammar.java b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/Grammar.java index 2f13a7448..e93117570 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/Grammar.java +++ b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/Grammar.java @@ -13,41 +13,39 @@ public record Grammar(Dictionary rules, NamedRule parse(ParseState parseState) { - return parseState.parseTopRule(this.top); + public Optional parse(ParseState state) { + return state.parseTopRule(this.top); } public T parse(StringReader reader) throws CommandSyntaxException { - ErrorCollector.LongestOnly longestOnly = new ErrorCollector.LongestOnly<>(); - StringReaderParserState stringReaderParserState = new StringReaderParserState(longestOnly, reader); - Optional optional = this.parse(stringReaderParserState); - if (optional.isPresent()) { - T result = optional.get(); + ErrorCollector.LongestOnly errorCollector = new ErrorCollector.LongestOnly<>(); + StringReaderParserState stringReaderParserState = new StringReaderParserState(errorCollector, reader); + Optional optionalResult = this.parse(stringReaderParserState); + if (optionalResult.isPresent()) { + T result = optionalResult.get(); if (CachedParseState.JAVA_NULL_VALUE_MARKER.equals(result)) { result = null; } return result; - } else { - List> list = longestOnly.entries(); - List list1 = list.stream().mapMulti((errorEntry, consumer) -> { - if (errorEntry.reason() instanceof DelayedException delayedException) { - consumer.accept(delayedException.create(reader.getString(), errorEntry.cursor())); - } else if (errorEntry.reason() instanceof Exception exception1) { - consumer.accept(exception1); - } - }).toList(); - - for (Exception exception : list1) { - if (exception instanceof CommandSyntaxException commandSyntaxException) { - throw commandSyntaxException; - } + } + List> errorEntries = errorCollector.entries(); + List exceptions = errorEntries.stream().mapMulti((entry, output) -> { + if (entry.reason() instanceof DelayedException delayedException) { + output.accept(delayedException.create(reader.getString(), entry.cursor())); + } else if (entry.reason() instanceof Exception exception1) { + output.accept(exception1); } + }).toList(); - if (list1.size() == 1 && list1.getFirst() instanceof RuntimeException runtimeException) { - throw runtimeException; - } else { - throw new IllegalStateException("Failed to parse: " + list.stream().map(ErrorEntry::toString).collect(Collectors.joining(", "))); + for (Exception exception : exceptions) { + if (exception instanceof CommandSyntaxException cse) { + throw cse; } } + + if (exceptions.size() == 1 && exceptions.getFirst() instanceof RuntimeException re) { + throw re; + } + throw new IllegalStateException("Failed to parse: " + errorEntries.stream().map(ErrorEntry::toString).collect(Collectors.joining(", "))); } } diff --git a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/GreedyPatternParseRule.java b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/GreedyPatternParseRule.java index 9d5e07b91..58bf9d797 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/GreedyPatternParseRule.java +++ b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/GreedyPatternParseRule.java @@ -19,16 +19,15 @@ public final class GreedyPatternParseRule implements Rule } @Override - public String parse(ParseState parseState) { - StringReader stringReader = parseState.input(); - String string = stringReader.getString(); - Matcher matcher = this.pattern.matcher(string).region(stringReader.getCursor(), string.length()); + public String parse(ParseState state) { + StringReader input = state.input(); + String fullString = input.getString(); + Matcher matcher = this.pattern.matcher(fullString).region(input.getCursor(), fullString.length()); if (!matcher.lookingAt()) { - parseState.errorCollector().store(parseState.mark(), this.error); + state.errorCollector().store(state.mark(), this.error); return null; - } else { - stringReader.setCursor(matcher.end()); - return matcher.group(0); } + input.setCursor(matcher.end()); + return matcher.group(0); } } diff --git a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/GreedyPredicateParseRule.java b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/GreedyPredicateParseRule.java index d3c8d8870..3144dcc27 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/GreedyPredicateParseRule.java +++ b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/GreedyPredicateParseRule.java @@ -25,24 +25,23 @@ public abstract class GreedyPredicateParseRule implements Rule parseState) { - StringReader stringReader = parseState.input(); - String string = stringReader.getString(); - int cursor = stringReader.getCursor(); - int i = cursor; + public String parse(ParseState state) { + StringReader input = state.input(); + String fullString = input.getString(); + int start = input.getCursor(); + int pos = start; - while (i < string.length() && this.isAccepted(string.charAt(i)) && i - cursor < this.maxSize) { - i++; + while (pos < fullString.length() && this.isAccepted(fullString.charAt(pos)) && pos - start < this.maxSize) { + pos++; } - int i1 = i - cursor; - if (i1 < this.minSize) { - parseState.errorCollector().store(parseState.mark(), this.error); + int length = pos - start; + if (length < this.minSize) { + state.errorCollector().store(state.mark(), this.error); return null; - } else { - stringReader.setCursor(i); - return string.substring(cursor, i); } + input.setCursor(pos); + return fullString.substring(start, pos); } protected abstract boolean isAccepted(char c); diff --git a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/NumberRunParseRule.java b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/NumberRunParseRule.java index 71a919544..dd4e6249b 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/NumberRunParseRule.java +++ b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/NumberRunParseRule.java @@ -19,28 +19,27 @@ public abstract class NumberRunParseRule implements Rule { @Nullable @Override - public String parse(ParseState parseState) { - StringReader stringReader = parseState.input(); - stringReader.skipWhitespace(); - String string = stringReader.getString(); - int cursor = stringReader.getCursor(); - int i = cursor; + public String parse(ParseState state) { + StringReader input = state.input(); + input.skipWhitespace(); + String fullString = input.getString(); + int start = input.getCursor(); + int pos = start; - while (i < string.length() && this.isAccepted(string.charAt(i))) { - i++; + while (pos < fullString.length() && this.isAccepted(fullString.charAt(pos))) { + pos++; } - int i1 = i - cursor; - if (i1 == 0) { - parseState.errorCollector().store(parseState.mark(), this.noValueError); - return null; - } else if (string.charAt(cursor) != '_' && string.charAt(i - 1) != '_') { - stringReader.setCursor(i); - return string.substring(cursor, i); - } else { - parseState.errorCollector().store(parseState.mark(), this.underscoreNotAllowedError); + int length = pos - start; + if (length == 0) { + state.errorCollector().store(state.mark(), this.noValueError); return null; + } else if (fullString.charAt(start) != '_' && fullString.charAt(pos - 1) != '_') { + input.setCursor(pos); + return fullString.substring(start, pos); } + state.errorCollector().store(state.mark(), this.underscoreNotAllowedError); + return null; } protected abstract boolean isAccepted(char c); diff --git a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/StringReaderParserState.java b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/StringReaderParserState.java index 9bf0a87b9..d076fafd4 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/StringReaderParserState.java +++ b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/StringReaderParserState.java @@ -23,7 +23,7 @@ public class StringReaderParserState extends CachedParseState { } @Override - public void restore(int cursor) { - this.input.setCursor(cursor); + public void restore(int mark) { + this.input.setCursor(mark); } } diff --git a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/StringReaderTerms.java b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/StringReaderTerms.java index 12cb7def3..14fe3f3aa 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/StringReaderTerms.java +++ b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/StringReaderTerms.java @@ -16,50 +16,49 @@ public interface StringReaderTerms { static Term character(final char value) { return new TerminalCharacters(CharList.of(value)) { @Override - protected boolean isAccepted(char c) { - return value == c; + protected boolean isAccepted(char v) { + return value == v; } }; } - static Term characters(final char value1, final char value2) { - return new TerminalCharacters(CharList.of(value1, value2)) { + static Term characters(final char v1, final char v2) { + return new TerminalCharacters(CharList.of(v1, v2)) { @Override - protected boolean isAccepted(char c) { - return c == value1 || c == value2; + protected boolean isAccepted(char v) { + return v == v1 || v == v2; } }; } - static StringReader createReader(String input, int cursor) { - StringReader stringReader = new StringReader(input); - stringReader.setCursor(cursor); - return stringReader; + static StringReader createReader(String contents, int cursor) { + StringReader reader = new StringReader(contents); + reader.setCursor(cursor); + return reader; } abstract class TerminalCharacters implements Term { private final DelayedException error; private final SuggestionSupplier suggestions; - public TerminalCharacters(CharList characters) { - String string = characters.intStream().mapToObj(Character::toString).collect(Collectors.joining("|")); - this.error = DelayedException.create(LITERAL_INCORRECT, string); - this.suggestions = parseState -> characters.intStream().mapToObj(Character::toString); + public TerminalCharacters(CharList values) { + String joinedValues = values.intStream().mapToObj(Character::toString).collect(Collectors.joining("|")); + this.error = DelayedException.create(LITERAL_INCORRECT, joinedValues); + this.suggestions = s -> values.intStream().mapToObj(Character::toString); } @Override - public boolean parse(ParseState parseState, Scope scope, Control control) { - parseState.input().skipWhitespace(); - int i = parseState.mark(); - if (parseState.input().canRead() && this.isAccepted(parseState.input().read())) { + public boolean parse(ParseState state, Scope scope, Control control) { + state.input().skipWhitespace(); + int cursor = state.mark(); + if (state.input().canRead() && this.isAccepted(state.input().read())) { return true; - } else { - parseState.errorCollector().store(i, this.suggestions, this.error); - return false; } + state.errorCollector().store(cursor, this.suggestions, this.error); + return false; } - protected abstract boolean isAccepted(char c); + protected abstract boolean isAccepted(char value); } } diff --git a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/UnquotedStringParseRule.java b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/UnquotedStringParseRule.java index 1909633c8..2d46092b7 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/UnquotedStringParseRule.java +++ b/core/src/main/java/net/momirealms/craftengine/core/util/snbt/parse/grammar/UnquotedStringParseRule.java @@ -19,15 +19,14 @@ public class UnquotedStringParseRule implements Rule { @Nullable @Override - public String parse(ParseState parseState) { - parseState.input().skipWhitespace(); - int i = parseState.mark(); - String unquotedString = parseState.input().readUnquotedString(); - if (unquotedString.length() < this.minSize) { - parseState.errorCollector().store(i, this.error); + public String parse(ParseState state) { + state.input().skipWhitespace(); + int cursor = state.mark(); + String value = state.input().readUnquotedString(); + if (value.length() < this.minSize) { + state.errorCollector().store(cursor, this.error); return null; - } else { - return unquotedString; } + return value; } }