Apache Solr open-source search software
LUCENE-5480: Hunspell shouldn't merge dictionary entries
Robert Muir242e554b9413
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/hunspell/Dictionary.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/hunspell/Dictionary.javaindex e62e662ddf2..5f9baf632d3 100644--- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/hunspell/Dictionary.java+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/hunspell/Dictionary.java@@ -26,11 +26,9 @@ import org.apache.lucene.util.IntsRef;import org.apache.lucene.util.OfflineSorter;import org.apache.lucene.util.OfflineSorter.ByteSequencesReader;import org.apache.lucene.util.OfflineSorter.ByteSequencesWriter;-import org.apache.lucene.util.UnicodeUtil;import org.apache.lucene.util.fst.Builder;import org.apache.lucene.util.fst.FST;import org.apache.lucene.util.fst.IntSequenceOutputs;-import org.apache.lucene.util.fst.PositiveIntOutputs;import org.apache.lucene.util.fst.Util;import java.io.BufferedInputStream;@@ -85,8 +83,8 @@ public class Dictionary {ArrayList<Pattern> patterns = new ArrayList<>();// the entries in the .dic file, mapping to their set of flags.- // the fst output is the ordinal for flagLookup- FST<Long> words;+ // the fst output is the ordinal list for flagLookup+ FST<IntsRef> words;// the list of unique flagsets (wordforms). theoretically huge, but practically// small (e.g. for polish this is 756), otherwise humans wouldn't be able to deal with it either.BytesRefHash flagLookup = new BytesRefHash();@@ -141,54 +139,17 @@ public class Dictionary {readAffixFile(buffered, decoder);flagLookup.add(new BytesRef()); // no flags -> ord 0stripLookup.add(new BytesRef()); // no strip -> ord 0- PositiveIntOutputs o = PositiveIntOutputs.getSingleton();- Builder<Long> b = new Builder<Long>(FST.INPUT_TYPE.BYTE4, o);+ IntSequenceOutputs o = IntSequenceOutputs.getSingleton();+ Builder<IntsRef> b = new Builder<IntsRef>(FST.INPUT_TYPE.BYTE4, o);readDictionaryFiles(dictionaries, decoder, b);words = b.finish();}/**- * Looks up words that match the String created from the given char array, offset and length- *- * @param word Char array to generate the String from- * @param offset Offset in the char array that the String starts at- * @param length Length from the offset that the String is- * @return List of HunspellWords that match the generated String, or {@code null} if none are found+ * Looks up Hunspell word forms from the dictionary*/- char[] lookupWord(char word[], int offset, int length, BytesRef scratch) {- Integer ord = null;- try {- ord = lookupOrd(word, offset, length);- } catch (IOException ex) { /* bogus */ }- if (ord == null) {- return null;- }- return decodeFlags(flagLookup.get(ord, scratch));- }-- Integer lookupOrd(char word[], int offset, int length) throws IOException {- final FST.BytesReader bytesReader = words.getBytesReader();- final FST.Arc<Long> arc = words.getFirstArc(new FST.Arc<Long>());- // Accumulate output as we go- final Long NO_OUTPUT = words.outputs.getNoOutput();- Long output = NO_OUTPUT;-- int l = offset + length;- for (int i = offset, cp = 0; i < l; i += Character.charCount(cp)) {- cp = Character.codePointAt(word, i, l);- if (words.findTargetArc(cp, arc, arc, bytesReader) == null) {- return null;- } else if (arc.output != NO_OUTPUT) {- output = words.outputs.add(output, arc.output);- }- }- if (words.findTargetArc(FST.END_LABEL, arc, arc, bytesReader) == null) {- return null;- } else if (arc.output != NO_OUTPUT) {- return words.outputs.add(output, arc.output).intValue();- } else {- return output.intValue();- }+ IntsRef lookupWord(char word[], int offset, int length) {+ return lookup(words, word, offset, length);}/**@@ -200,7 +161,7 @@ public class Dictionary {* @return List of HunspellAffix prefixes with an append that matches the String, or {@code null} if none are found*/IntsRef lookupPrefix(char word[], int offset, int length) {- return lookupAffix(prefixes, word, offset, length);+ return lookup(prefixes, word, offset, length);}/**@@ -212,12 +173,12 @@ public class Dictionary {* @return List of HunspellAffix suffixes with an append that matches the String, or {@code null} if none are found*/IntsRef lookupSuffix(char word[], int offset, int length) {- return lookupAffix(suffixes, word, offset, length);+ return lookup(suffixes, word, offset, length);}// TODO: this is pretty stupid, considering how the stemming algorithm works// we can speed it up to be significantly faster!- IntsRef lookupAffix(FST<IntsRef> fst, char word[], int offset, int length) {+ IntsRef lookup(FST<IntsRef> fst, char word[], int offset, int length) {if (fst == null) {return null;}@@ -506,7 +467,7 @@ public class Dictionary {* @param decoder CharsetDecoder used to decode the contents of the file* @throws IOException Can be thrown while reading from the file*/- private void readDictionaryFiles(List<InputStream> dictionaries, CharsetDecoder decoder, Builder<Long> words) throws IOException {+ private void readDictionaryFiles(List<InputStream> dictionaries, CharsetDecoder decoder, Builder<IntsRef> words) throws IOException {BytesRef flagsScratch = new BytesRef();IntsRef scratchInts = new IntsRef();@@ -565,7 +526,13 @@ public class Dictionary {}}- return scratch1.compareTo(scratch2);+ int cmp = scratch1.compareTo(scratch2);+ if (cmp == 0) {+ // tie break on whole row+ return o1.compareTo(o2);+ } else {+ return cmp;+ }}});sorter.sort(unsorted, sorted);@@ -577,8 +544,8 @@ public class Dictionary {// TODO: the flags themselves can be double-chars (long) or also numeric// either way the trick is to encode them as char... but they must be parsed differently- BytesRef currentEntry = new BytesRef();- char currentFlags[] = new char[0];+ String currentEntry = null;+ IntsRef currentOrds = new IntsRef();String line;while (reader.read(scratchLine)) {@@ -592,10 +559,14 @@ public class Dictionary {entry = line;} else {// note, there can be comments (morph description) after a flag.- // we should really look for any whitespace+ // we should really look for any whitespace: currently just tab and spaceint end = line.indexOf('\t', flagSep);if (end == -1)end = line.length();+ int end2 = line.indexOf(' ', flagSep);+ if (end2 == -1)+ end2 = line.length();+ end = Math.min(end, end2);String flagPart = line.substring(flagSep + 1, end);if (aliasCount > 0) {@@ -607,34 +578,34 @@ public class Dictionary {entry = line.substring(0, flagSep);}- BytesRef scratch = new BytesRef(entry);- int cmp = scratch.compareTo(currentEntry);+ int cmp = currentEntry == null ? 1 : entry.compareTo(currentEntry);if (cmp < 0) {- throw new IllegalArgumentException("out of order: " + scratch.utf8ToString() + " < " + currentEntry.utf8ToString());- } else if (cmp == 0) {- currentFlags = merge(currentFlags, wordForm);+ throw new IllegalArgumentException("out of order: " + entry + " < " + currentEntry);} else {- final int hashCode = encodeFlagsWithHash(flagsScratch, currentFlags);+ final int hashCode = encodeFlagsWithHash(flagsScratch, wordForm);int ord = flagLookup.add(flagsScratch, hashCode);if (ord < 0) {// already exists in our hashord = (-ord)-1;}- UnicodeUtil.UTF8toUTF32(currentEntry, scratchInts);- words.add(scratchInts, (long)ord);- currentEntry = scratch;- currentFlags = wordForm;+ // finalize current entry, and switch "current" if necessary+ if (cmp > 0 && currentEntry != null) {+ Util.toUTF32(currentEntry, scratchInts);+ words.add(scratchInts, currentOrds);+ }+ // swap current+ if (cmp > 0 || currentEntry == null) {+ currentEntry = entry;+ currentOrds = new IntsRef(); // must be this way+ }+ currentOrds.grow(currentOrds.length+1);+ currentOrds.ints[currentOrds.length++] = ord;}}- final int hashCode = encodeFlagsWithHash(flagsScratch, currentFlags);- int ord = flagLookup.add(flagsScratch, hashCode);- if (ord < 0) {- // already exists in our hash- ord = (-ord)-1;- }- UnicodeUtil.UTF8toUTF32(currentEntry, scratchInts);- words.add(scratchInts, (long)ord);+ // finalize last entry+ Util.toUTF32(currentEntry, scratchInts);+ words.add(scratchInts, currentOrds);reader.close();sorted.delete();@@ -776,46 +747,4 @@ public class Dictionary {static boolean hasFlag(char flags[], char flag) {return Arrays.binarySearch(flags, flag) >= 0;}-- static char[] merge(char[] flags1, char[] flags2) {- char merged[] = new char[flags1.length + flags2.length];- int i1 = 0, i2 = 0;- int last = -1;- int upto = 0;-- while (i1 < flags1.length && i2 < flags2.length) {- final char next;- if (flags1[i1] <= flags2[i2]) {- next = flags1[i1++];- } else {- next = flags2[i2++];- }- if (next != last) {- merged[upto++] = next;- last = next;- }- }-- while (i1 < flags1.length) {- char next = flags1[i1++];- if (next != last) {- merged[upto++] = next;- last = next;- }- }-- while (i2 < flags2.length) {- char next = flags2[i2++];- if (next != last) {- merged[upto++] = next;- last = next;- }- }-- if (merged.length != upto) {- merged = Arrays.copyOf(merged, upto);- }-- return merged;- }}diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/hunspell/Stemmer.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/hunspell/Stemmer.javaindex 18e6588ce7a..d8bd1a16cd7 100644--- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/hunspell/Stemmer.java+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/hunspell/Stemmer.java@@ -86,8 +86,13 @@ final class Stemmer {charUtils.toLowerCase(word, 0, length);}List<CharsRef> stems = new ArrayList<CharsRef>();- if (dictionary.lookupWord(word, 0, length, scratch) != null) {- stems.add(new CharsRef(word, 0, length));+ IntsRef forms = dictionary.lookupWord(word, 0, length);+ if (forms != null) {+ // TODO: some forms should not be added, e.g. ONLYINCOMPOUND+ // just because it exists, does not make it valid...+ for (int i = 0; i < forms.length; i++) {+ stems.add(new CharsRef(word, 0, length));+ }}stems.addAll(stem(word, length, Dictionary.NOFLAGS, 0));return stems;@@ -203,7 +208,7 @@ final class Stemmer {boolean crossProduct = (condition & 1) == 1;condition >>>= 1;char append = (char) (affixReader.readShort() & 0xffff);-+Pattern pattern = dictionary.patterns.get(condition);if (!pattern.matcher(segment).matches()) {return Collections.emptyList();@@ -211,9 +216,15 @@ final class Stemmer {List<CharsRef> stems = new ArrayList<CharsRef>();- char wordFlags[] = dictionary.lookupWord(strippedWord, 0, length, scratch);- if (wordFlags != null && Dictionary.hasFlag(wordFlags, flag)) {- stems.add(new CharsRef(strippedWord, 0, length));+ IntsRef forms = dictionary.lookupWord(strippedWord, 0, length);+ if (forms != null) {+ for (int i = 0; i < forms.length; i++) {+ dictionary.flagLookup.get(forms.ints[forms.offset+i], scratch);+ char wordFlags[] = Dictionary.decodeFlags(scratch);+ if (wordFlags != null && Dictionary.hasFlag(wordFlags, flag)) {+ stems.add(new CharsRef(strippedWord, 0, length));+ }+ }}if (crossProduct && recursionDepth < recursionCap) {diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/StemmerTestBase.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/StemmerTestBase.javaindex 67b1eca66cd..083ae26ac76 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/StemmerTestBase.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/StemmerTestBase.java@@ -74,6 +74,6 @@ abstract class StemmerTestBase extends LuceneTestCase {}Arrays.sort(actual);- assertArrayEquals(expected, actual);+ assertArrayEquals("expected=" + Arrays.toString(expected) + ",actual=" + Arrays.toString(actual), expected, actual);}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestCaseInsensitive.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestCaseInsensitive.javaindex b1e7c1347ee..01a30a77b24 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestCaseInsensitive.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestCaseInsensitive.java@@ -47,7 +47,7 @@ public class TestCaseInsensitive extends StemmerTestBase {assertStemsTo("abc", "ab");assertStemsTo("apach", "apach");assertStemsTo("apache", "apach");- assertStemsTo("foo", "foo");+ assertStemsTo("foo", "foo", "foo");assertStemsTo("food", "foo");assertStemsTo("foos", "foo");assertStemsTo("lucen", "lucen");diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestDependencies.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestDependencies.javanew file mode 100644index 00000000000..7fd855b92fd--- /dev/null+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestDependencies.java@@ -0,0 +1,39 @@+package org.apache.lucene.analysis.hunspell;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import org.junit.BeforeClass;++public class TestDependencies extends StemmerTestBase {++ @BeforeClass+ public static void beforeClass() throws Exception {+ init("dependencies.aff", "dependencies.dic");+ }++ public void testDependencies() {+ assertStemsTo("drink", "drink", "drink");+ assertStemsTo("drinks", "drink", "drink");+ assertStemsTo("drinkable", "drink");+ // TODO: BUG! assertStemsTo("drinkables", "drink");+ assertStemsTo("undrinkable", "drink");+ // TODO: BUG! assertStemsTo("undrinkables", "drink");+ assertStemsTo("undrink");+ // TODO: BUG! assertStemsTo("undrinks");+ }+}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestDictionary.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestDictionary.javaindex 6cbe931d376..b65283103c4 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestDictionary.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestDictionary.java@@ -24,6 +24,7 @@ import java.text.ParseException;import org.apache.lucene.analysis.hunspell.Dictionary;import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.IntsRef;import org.apache.lucene.util.LuceneTestCase;public class TestDictionary extends LuceneTestCase {@@ -35,11 +36,22 @@ public class TestDictionary extends LuceneTestCase {Dictionary dictionary = new Dictionary(affixStream, dictStream);assertEquals(3, dictionary.lookupSuffix(new char[]{'e'}, 0, 1).length);assertEquals(1, dictionary.lookupPrefix(new char[]{'s'}, 0, 1).length);- char flags[] = dictionary.lookupWord(new char[]{'o', 'l', 'r'}, 0, 3, new BytesRef());- assertNotNull(flags);+ IntsRef ordList = dictionary.lookupWord(new char[]{'o', 'l', 'r'}, 0, 3);+ assertNotNull(ordList);+ assertEquals(1, ordList.length);++ BytesRef ref = new BytesRef();+ dictionary.flagLookup.get(ordList.ints[0], ref);+ char flags[] = Dictionary.decodeFlags(ref);assertEquals(1, flags.length);- assertEquals("Wrong number of flags for lucen", 1, dictionary.lookupWord(new char[]{'l', 'u', 'c', 'e', 'n'}, 0, 5, new BytesRef()).length);-++ ordList = dictionary.lookupWord(new char[]{'l', 'u', 'c', 'e', 'n'}, 0, 5);+ assertNotNull(ordList);+ assertEquals(1, ordList.length);+ dictionary.flagLookup.get(ordList.ints[0], ref);+ flags = Dictionary.decodeFlags(ref);+ assertEquals(1, flags.length);+affixStream.close();dictStream.close();}@@ -51,7 +63,11 @@ public class TestDictionary extends LuceneTestCase {Dictionary dictionary = new Dictionary(affixStream, dictStream);assertEquals(3, dictionary.lookupSuffix(new char[]{'e'}, 0, 1).length);assertEquals(1, dictionary.lookupPrefix(new char[]{'s'}, 0, 1).length);- assertEquals(1, dictionary.lookupWord(new char[]{'o', 'l', 'r'}, 0, 3, new BytesRef()).length);+ IntsRef ordList = dictionary.lookupWord(new char[]{'o', 'l', 'r'}, 0, 3);+ BytesRef ref = new BytesRef();+ dictionary.flagLookup.get(ordList.ints[0], ref);+ char flags[] = Dictionary.decodeFlags(ref);+ assertEquals(1, flags.length);affixStream.close();dictStream.close();diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestHomonyms.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestHomonyms.javanew file mode 100644index 00000000000..73c73890467--- /dev/null+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestHomonyms.java@@ -0,0 +1,32 @@+package org.apache.lucene.analysis.hunspell;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import org.junit.BeforeClass;++public class TestHomonyms extends StemmerTestBase {++ @BeforeClass+ public static void beforeClass() throws Exception {+ init("homonyms.aff", "homonyms.dic");+ }++ public void testExamples() {+ assertStemsTo("works", "work", "work");+ }+}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestStemmer.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestStemmer.javaindex 19a5e2a3d6d..71a5bee181c 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestStemmer.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestStemmer.java@@ -45,7 +45,7 @@ public class TestStemmer extends StemmerTestBase {assertStemsTo("abc", "ab");assertStemsTo("apach", "apach");assertStemsTo("apache", "apach");- assertStemsTo("foo", "foo");+ assertStemsTo("foo", "foo", "foo");assertStemsTo("food", "foo");assertStemsTo("foos", "foo");assertStemsTo("lucen", "lucen");diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestTwoFold.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestTwoFold.javaindex 313b4ded1a9..1a65cfcaad9 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestTwoFold.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestTwoFold.java@@ -30,5 +30,6 @@ public class TestTwoFold extends StemmerTestBase {assertStemsTo("drink", "drink");assertStemsTo("drinkable", "drink");assertStemsTo("drinkables", "drink");+ assertStemsTo("drinksable");}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/dependencies.aff b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/dependencies.affnew file mode 100644index 00000000000..5589f3f3ed0--- /dev/null+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/dependencies.aff@@ -0,0 +1,13 @@+SET UTF-8++PFX P Y 1+PFX P 0 un . [prefix_un]+++SFX S Y 1+SFX S 0 s . +PL++SFX Q Y 1+SFX Q 0 s . +3SGV++SFX R Y 1+SFX R 0 able/PS . +DER_V_ADJ_ABLE\ No newline at end of filediff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/dependencies.dic b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/dependencies.dicnew file mode 100644index 00000000000..bdba45e044d--- /dev/null+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/dependencies.dic@@ -0,0 +1,3 @@+2+drink/RQ [verb]+drink/S [noun]diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/homonyms.aff b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/homonyms.affnew file mode 100644index 00000000000..43b4bb1d2cc--- /dev/null+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/homonyms.aff@@ -0,0 +1,7 @@+SET UTF-8++SFX A Y 1+SFX A 0 s . +SG3++SFX B Y 1+SFX B 0 s . +PLURdiff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/homonyms.dic b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/homonyms.dicnew file mode 100644index 00000000000..96d51f14f91--- /dev/null+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/homonyms.dic@@ -0,0 +1,3 @@+2+work/A [VERB]+work/B [NOUN]\ No newline at end of file