Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert more classes to record classes #13328

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,15 @@ public String toString() {

boolean prohibitsCompounding(CharsRef word, int breakPos, Root<?> rootBefore, Root<?> rootAfter) {
if (isNonAffixedPattern(endChars)) {
if (!charsMatch(word, breakPos - rootBefore.word.length(), rootBefore.word)) {
if (!charsMatch(word, breakPos - rootBefore.word().length(), rootBefore.word())) {
return false;
}
} else if (!charsMatch(word, breakPos - endChars.length(), endChars)) {
return false;
}

if (isNonAffixedPattern(beginChars)) {
if (!charsMatch(word, breakPos, rootAfter.word)) {
if (!charsMatch(word, breakPos, rootAfter.word())) {
return false;
}
} else if (!charsMatch(word, breakPos, beginChars)) {
Expand All @@ -84,7 +84,7 @@ private static boolean isNonAffixedPattern(String pattern) {

private boolean hasAllFlags(Root<?> root, char[] flags) {
for (char flag : flags) {
if (!dictionary.hasFlag(root.entryId, flag)) {
if (!dictionary.hasFlag(root.entryId(), flag)) {
return false;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.TreeSet;
Expand Down Expand Up @@ -111,7 +110,7 @@ private List<Weighted<Root<String>>> findSimilarDictionaryEntries(

private static boolean isWorseThan(int score, CharsRef candidate, Weighted<Root<String>> root) {
return score < root.score
|| score == root.score && CharSequence.compare(candidate, root.word.word) > 0;
|| score == root.score && CharSequence.compare(candidate, root.word.word()) > 0;
}

private void processSuggestibleWords(
Expand Down Expand Up @@ -162,11 +161,11 @@ private List<String> expandRoot(Root<String> root, String misspelled) {
List<char[]> crossProducts = new ArrayList<>();
Set<String> result = new LinkedHashSet<>();

if (!dictionary.hasFlag(root.entryId, dictionary.needaffix)) {
result.add(root.word);
if (!dictionary.hasFlag(root.entryId(), dictionary.needaffix)) {
result.add(root.word());
}

char[] wordChars = root.word.toCharArray();
char[] wordChars = root.word().toCharArray();

// suffixes
processAffixes(
Expand All @@ -180,7 +179,7 @@ private List<String> expandRoot(Root<String> root, String misspelled) {
}

String suffix = misspelled.substring(misspelled.length() - suffixLength);
String withSuffix = root.word.substring(0, root.word.length() - stripLength) + suffix;
String withSuffix = root.word().substring(0, root.word().length() - stripLength) + suffix;
result.add(withSuffix);
if (dictionary.isCrossProduct(suffixId)) {
crossProducts.add(withSuffix.toCharArray());
Expand All @@ -192,7 +191,7 @@ private List<String> expandRoot(Root<String> root, String misspelled) {
true,
misspelled,
(prefixLength, prefixId) -> {
if (!dictionary.hasFlag(root.entryId, dictionary.affixData(prefixId, AFFIX_FLAG))
if (!dictionary.hasFlag(root.entryId(), dictionary.affixData(prefixId, AFFIX_FLAG))
|| !dictionary.isCrossProduct(prefixId)) {
return;
}
Expand All @@ -217,7 +216,7 @@ private List<String> expandRoot(Root<String> root, String misspelled) {
if (hasCompatibleFlags(root, prefixId)
&& checkAffixCondition(prefixId, wordChars, stripLength, stemLength)) {
String prefix = misspelled.substring(0, prefixLength);
result.add(prefix + root.word.substring(stripLength));
result.add(prefix + root.word().substring(stripLength));
}
});

Expand Down Expand Up @@ -263,7 +262,7 @@ private interface AffixProcessor {
}

private boolean hasCompatibleFlags(Root<?> root, int affixId) {
if (!dictionary.hasFlag(root.entryId, dictionary.affixData(affixId, AFFIX_FLAG))) {
if (!dictionary.hasFlag(root.entryId(), dictionary.affixData(affixId, AFFIX_FLAG))) {
return false;
}

Expand Down Expand Up @@ -447,28 +446,8 @@ private static int commonCharacterPositionScore(String s1, String s2) {
return commonScore;
}

private static class Weighted<T extends Comparable<T>> implements Comparable<Weighted<T>> {
final T word;
final int score;

Weighted(T word, int score) {
this.word = word;
this.score = score;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Weighted)) return false;
@SuppressWarnings("unchecked")
Weighted<T> that = (Weighted<T>) o;
return score == that.score && word.equals(that.word);
}

@Override
public int hashCode() {
return Objects.hash(word, score);
}
private record Weighted<T extends Comparable<T>>(T word, int score)
implements Comparable<Weighted<T>> {

@Override
public String toString() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ boolean checkWord(String word) {
Boolean checkSimpleWord(char[] wordChars, int length, WordCase originalCase) {
Root<CharsRef> entry = findStem(wordChars, 0, length, originalCase, SIMPLE_WORD);
if (entry != null) {
return !dictionary.hasFlag(entry.entryId, dictionary.forbiddenword);
return !dictionary.hasFlag(entry.entryId(), dictionary.forbiddenword);
}

return null;
Expand Down Expand Up @@ -229,7 +229,7 @@ private boolean checkCompounds(CharsRef word, WordCase originalCase, CompoundPar
stem = findStem(word.chars, word.offset, breakPos + 1, originalCase, context);
}
if (stem != null
&& !dictionary.hasFlag(stem.entryId, dictionary.forbiddenword)
&& !dictionary.hasFlag(stem.entryId(), dictionary.forbiddenword)
&& (prev == null || prev.mayCompound(stem, breakPos, originalCase))) {
CompoundPart part = new CompoundPart(prev, word, breakPos, stem, null);
if (checkCompoundsAfter(originalCase, part)) {
Expand Down Expand Up @@ -274,7 +274,7 @@ private boolean checkCompoundsAfter(WordCase originalCase, CompoundPart prev) {
Root<CharsRef> lastRoot =
findStem(word.chars, breakOffset, remainingLength, originalCase, COMPOUND_END);
if (lastRoot != null
&& !dictionary.hasFlag(lastRoot.entryId, dictionary.forbiddenword)
&& !dictionary.hasFlag(lastRoot.entryId(), dictionary.forbiddenword)
&& !(dictionary.checkCompoundDup && prev.root.equals(lastRoot))
&& !hasForceUCaseProblem(lastRoot, originalCase, word.chars)
&& prev.mayCompound(lastRoot, remainingLength, originalCase)) {
Expand All @@ -288,7 +288,7 @@ private boolean checkCompoundsAfter(WordCase originalCase, CompoundPart prev) {
private boolean hasForceUCaseProblem(Root<?> root, WordCase originalCase, char[] wordChars) {
if (originalCase == WordCase.TITLE || originalCase == WordCase.UPPER) return false;
if (originalCase == null && Character.isUpperCase(wordChars[0])) return false;
return dictionary.hasFlag(root.entryId, dictionary.forceUCase);
return dictionary.hasFlag(root.entryId(), dictionary.forceUCase);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,36 +16,13 @@
*/
package org.apache.lucene.analysis.hunspell;

import java.util.Objects;

class Root<T extends CharSequence> implements Comparable<Root<T>> {
final T word;
final int entryId;

Root(T word, int entryId) {
this.word = word;
this.entryId = entryId;
}
record Root<T extends CharSequence>(T word, int entryId) implements Comparable<Root<T>> {

@Override
public String toString() {
return word.toString();
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Root)) return false;
@SuppressWarnings("unchecked")
Root<T> root = (Root<T>) o;
return entryId == root.entryId && word.equals(root.word);
}

@Override
public int hashCode() {
return Objects.hash(word, entryId);
}

@Override
public int compareTo(Root<T> o) {
return CharSequence.compare(word, o.word);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,12 @@ public PatternTypingFilter(TokenStream input, PatternTypingRule... replacementAn
public final boolean incrementToken() throws IOException {
if (input.incrementToken()) {
for (PatternTypingRule rule : replacementAndFlagByPattern) {
Matcher matcher = rule.getPattern().matcher(termAtt);
Matcher matcher = rule.pattern().matcher(termAtt);
if (matcher.find()) {
// allow 2nd reset() and find() that occurs inside replaceFirst to avoid excess string
// creation
typeAtt.setType(matcher.replaceFirst(rule.getTypeTemplate()));
flagAtt.setFlags(rule.getFlags());
typeAtt.setType(matcher.replaceFirst(rule.typeTemplate()));
flagAtt.setFlags(rule.flags());
return true;
}
}
Expand All @@ -74,27 +74,5 @@ public final boolean incrementToken() throws IOException {
}

/** Value holding class for pattern typing rules. */
public static class PatternTypingRule {
private final Pattern pattern;
private final int flags;
private final String typeTemplate;

public PatternTypingRule(Pattern pattern, int flags, String typeTemplate) {
this.pattern = pattern;
this.flags = flags;
this.typeTemplate = typeTemplate;
}

public Pattern getPattern() {
return pattern;
}

public int getFlags() {
return flags;
}

public String getTypeTemplate() {
return typeTemplate;
}
}
public record PatternTypingRule(Pattern pattern, int flags, String typeTemplate) {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -142,22 +142,10 @@ public void reset() {
}
}

static class BufferedOutputToken {
final String term;

// Non-null if this was an incoming token:
final State state;

final int startNode;
final int endNode;

public BufferedOutputToken(State state, String term, int startNode, int endNode) {
this.state = state;
this.term = term;
this.startNode = startNode;
this.endNode = endNode;
}
}
/**
* @param state Non-null if this was an incoming token:
*/
record BufferedOutputToken(State state, String term, int startNode, int endNode) {}

/**
* Apply previously built synonyms to incoming tokens.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,15 @@

import org.apache.lucene.util.BytesRef;

/** Wraps a term and boost */
public class TermAndBoost {
/** the term */
public final BytesRef term;

/** the boost */
public final float boost;

/**
* Wraps a term and boost
*
* @param term the term
* @param boost the boost
*/
public record TermAndBoost(BytesRef term, float boost) {
/** Creates a new TermAndBoost */
public TermAndBoost(BytesRef term, float boost) {
this.term = BytesRef.deepCopyOf(term);
this.boost = boost;
public TermAndBoost {
term = BytesRef.deepCopyOf(term);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public boolean incrementToken() throws IOException {
clearAttributes();
restoreState(this.lastState);
termAtt.setEmpty();
termAtt.append(synonym.term.utf8ToString());
termAtt.append(synonym.term().utf8ToString());
typeAtt.setType(SynonymGraphFilter.TYPE_SYNONYM);
posLenAtt.setPositionLength(1);
posIncrementAtt.setPositionIncrement(0);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public void getSynonyms_shouldReturnSynonymsBasedOnMinAcceptedSimilarity() throw

assertEquals(4, actualSynonymsResults.size());
for (int i = 0; i < expectedSynonyms.length; i++) {
assertEquals(new BytesRef(expectedSynonyms[i]), actualSynonymsResults.get(i).term);
assertEquals(new BytesRef(expectedSynonyms[i]), actualSynonymsResults.get(i).term());
}
}

Expand All @@ -83,8 +83,8 @@ public void getSynonyms_shouldReturnSynonymsBoost() throws Exception {

BytesRef expectedFirstSynonymTerm = new BytesRef("b");
double expectedFirstSynonymBoost = 1.0;
assertEquals(expectedFirstSynonymTerm, actualSynonymsResults.get(0).term);
assertEquals(expectedFirstSynonymBoost, actualSynonymsResults.get(0).boost, 0.001f);
assertEquals(expectedFirstSynonymTerm, actualSynonymsResults.get(0).term());
assertEquals(expectedFirstSynonymBoost, actualSynonymsResults.get(0).boost(), 0.001f);
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,19 +139,7 @@ private void mayIncrementToken() throws IOException {
}
}

private static class CompletionToken {
final String term;
final boolean isFirst;
final int startOffset;
final int endOffset;

CompletionToken(String term, boolean isFirst, int startOffset, int endOffset) {
this.term = term;
this.isFirst = isFirst;
this.startOffset = startOffset;
this.endOffset = endOffset;
}
}
private record CompletionToken(String term, boolean isFirst, int startOffset, int endOffset) {}

private static class CompletionTokenGenerator implements Iterator<CompletionToken> {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,13 +180,5 @@ private MatchedKeystroke longestKeystrokeMatch(CharsRef input, int inputOffset)
return null;
}

private static class MatchedKeystroke {
final int keystrokeLen;
final int keystrokeIndex;

MatchedKeystroke(int keystrokeLen, int keystrokeIndex) {
this.keystrokeLen = keystrokeLen;
this.keystrokeIndex = keystrokeIndex;
}
}
private record MatchedKeystroke(int keystrokeLen, int keystrokeIndex) {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -268,19 +268,19 @@ protected void backtrace(Position endPosData, int fromIDX) {
final KoMorphData.Morpheme morpheme = morphemes[i];
final Token compoundToken;
if (token.getPOSType() == POS.Type.COMPOUND) {
assert endOffset - morpheme.surfaceForm.length() >= 0;
assert endOffset - morpheme.surfaceForm().length() >= 0;
compoundToken =
new DecompoundToken(
morpheme.posTag,
morpheme.surfaceForm,
endOffset - morpheme.surfaceForm.length(),
morpheme.posTag(),
morpheme.surfaceForm(),
endOffset - morpheme.surfaceForm().length(),
endOffset,
backType);
} else {
compoundToken =
new DecompoundToken(
morpheme.posTag,
morpheme.surfaceForm,
morpheme.posTag(),
morpheme.surfaceForm(),
token.getStartOffset(),
token.getEndOffset(),
backType);
Expand All @@ -289,7 +289,7 @@ protected void backtrace(Position endPosData, int fromIDX) {
compoundToken.setPositionIncrement(0);
}
++posLen;
endOffset -= morpheme.surfaceForm.length();
endOffset -= morpheme.surfaceForm().length();
pending.add(compoundToken);
if (VERBOSE) {
System.out.println(" add token=" + pending.get(pending.size() - 1));
Expand Down