xapian-core  2.1.0
glass_spelling.cc
Go to the documentation of this file.
1 
4 /* Copyright (C) 2004-2026 Olly Betts
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, see
18  * <https://www.gnu.org/licenses/>.
19  */
20 
21 #include <config.h>
22 
23 #include <xapian/error.h>
24 #include <xapian/types.h>
25 
26 #include "clamp_cast.h"
27 #include "expand/expandweight.h"
28 #include "expand/termlistmerger.h"
29 #include "glass_spelling.h"
30 #include "omassert.h"
31 #include "pack.h"
32 
33 #include "../prefix_compressed_strings.h"
34 
35 #include <algorithm>
36 #include <map>
37 #include <queue>
38 #include <vector>
39 #include <set>
40 #include <string>
41 #include <string_view>
42 
43 using namespace Glass;
44 using namespace std;
45 
46 void
48 {
49  for (auto i : termlist_deltas) {
50  const string& key = i.first;
51  const set<string>& changes = i.second;
52 
53  auto d = changes.begin();
54  if (d == changes.end()) continue;
55 
56  string updated;
57  string current;
58  PrefixCompressedStringWriter out(updated);
59  if (get_exact_entry(key, current)) {
60  PrefixCompressedStringItor in(current);
61  updated.reserve(current.size()); // FIXME plus some?
62  while (!in.at_end() && d != changes.end()) {
63  const string & word = *in;
64  Assert(d != changes.end());
65  int cmp = word.compare(*d);
66  if (cmp < 0) {
67  out.append(word);
68  ++in;
69  } else if (cmp > 0) {
70  out.append(*d);
71  ++d;
72  } else {
73  // If an existing entry is in the changes list, that means
74  // we should remove it.
75  ++in;
76  ++d;
77  }
78  }
79  if (!in.at_end()) {
80  // FIXME : easy to optimise this to a fix-up and substring copy.
81  while (!in.at_end()) {
82  out.append(*in++);
83  }
84  }
85  }
86  while (d != changes.end()) {
87  out.append(*d++);
88  }
89  if (!updated.empty()) {
90  add(key, updated);
91  } else {
92  del(key);
93  }
94  }
95  termlist_deltas.clear();
96 
97  for (auto&& j : wordfreq_changes) {
98  string key = "W" + j.first;
99  Xapian::termcount wordfreq = j.second;
100  if (wordfreq) {
101  string tag;
102  pack_uint_last(tag, wordfreq);
103  add(key, tag);
104  if (wordfreq > wordfreq_upper_bound)
105  wordfreq_upper_bound = wordfreq;
106  } else {
107  del(key);
108  }
109  }
110  wordfreq_changes.clear();
111 }
112 
113 void
115 {
116  auto i = termlist_deltas.find(frag);
117  if (i == termlist_deltas.end()) {
118  i = termlist_deltas.insert(make_pair(frag, set<string>())).first;
119  }
120  // The commonest case is that we're adding lots of words, so try insert
121  // first and if that reports that the word already exists, remove it.
122  auto res = i->second.emplace(word);
123  if (!res.second) {
124  // word is already in the set, so remove it.
125  i->second.erase(res.first);
126  }
127 }
128 
129 void
131 {
132  if (word.size() <= 1) return;
133 
134  auto i = wordfreq_changes.find(word);
135  if (i != wordfreq_changes.end()) {
136  // Word "word" already exists and has been modified.
137  if (i->second) {
138  i->second += freqinc;
139  return;
140  }
141  // If "word" is currently modified such that it no longer exists, so
142  // we need to execute the code below to re-add trigrams for it.
143  i->second = freqinc;
144  } else {
145  string key = "W"s.append(word);
146  string data;
147  if (get_exact_entry(key, data)) {
148  // Word "word" already exists, so increment its count.
149  Xapian::termcount freq;
150  const char * p = data.data();
151  if (!unpack_uint_last(&p, p + data.size(), &freq) || freq == 0) {
152  throw Xapian::DatabaseCorruptError("Bad spelling word freq");
153  }
154  wordfreq_changes.emplace(word, freq + freqinc);
155  return;
156  }
157  wordfreq_changes.emplace(word, freqinc);
158  }
159 
160  // Add trigrams for word.
161  toggle_word(word);
162 }
163 
166 {
167  if (word.size() <= 1) return freqdec;
168 
169  auto i = wordfreq_changes.find(word);
170  if (i != wordfreq_changes.end()) {
171  if (i->second == 0) {
172  // Word has already been deleted.
173  return freqdec;
174  }
175  // Word "word" exists and has been modified.
176  if (freqdec < i->second) {
177  i->second -= freqdec;
178  return 0;
179  }
180  freqdec -= i->second;
181 
182  // Mark word as deleted.
183  i->second = 0;
184  } else {
185  string key = "W"s.append(word);
186  string data;
187  if (!get_exact_entry(key, data)) {
188  // This word doesn't exist.
189  return freqdec;
190  }
191 
192  Xapian::termcount freq;
193  const char *p = data.data();
194  if (!unpack_uint_last(&p, p + data.size(), &freq)) {
195  throw Xapian::DatabaseCorruptError("Bad spelling word freq");
196  }
197  if (freqdec < freq) {
198  wordfreq_changes.emplace(word, freq - freqdec);
199  return 0;
200  }
201  freqdec -= freq;
202 
203  // Mark word as deleted.
204  wordfreq_changes.emplace(word, 0);
205  }
206 
207  // Remove trigrams for word.
208  toggle_word(word);
209 
210  return freqdec;
211 }
212 
213 void
215 {
216  fragment buf;
217  // Head:
218  buf[0] = 'H';
219  buf[1] = word[0];
220  buf[2] = word[1];
221  buf[3] = '\0';
222  toggle_fragment(buf, word);
223 
224  // Tail:
225  buf[0] = 'T';
226  buf[1] = word[word.size() - 2];
227  buf[2] = word[word.size() - 1];
228  buf[3] = '\0';
229  toggle_fragment(buf, word);
230 
231  if (word.size() <= 4) {
232  // We also generate 'bookends' for two, three, and four character
233  // terms so we can handle transposition of the middle two characters
234  // of a four character word, substitution or deletion of the middle
235  // character of a three character word, or insertion in the middle of a
236  // two character word.
237  // 'Bookends':
238  buf[0] = 'B';
239  buf[1] = word[0];
240  buf[3] = '\0';
241  toggle_fragment(buf, word);
242  }
243  if (word.size() > 2) {
244  set<fragment> done;
245  // Middles:
246  buf[0] = 'M';
247  for (size_t start = 0; start <= word.size() - 3; ++start) {
248  memcpy(buf.data + 1, word.data() + start, 3);
249  // Don't toggle the same fragment twice or it will cancel out.
250  // Bug fixed in 1.2.6.
251  if (done.insert(buf).second)
252  toggle_fragment(buf, word);
253  }
254  }
255 }
256 
258  bool operator()(const TermList *a, const TermList *b) const {
259  return a->get_approx_size() > b->get_approx_size();
260  }
261 };
262 
263 TermList*
265 {
266  // This should have been handled by Database::get_spelling_suggestion().
267  AssertRel(word.size(),>,1);
268 
269  // Merge any pending changes to disk, but don't call commit() so they
270  // won't be switched live.
271  if (!wordfreq_changes.empty()) merge_changes();
272 
273  vector<TermList*> termlists;
274  try {
275  string data;
276  fragment buf;
277 
278  // Head:
279  buf[0] = 'H';
280  buf[1] = word[0];
281  buf[2] = word[1];
282  if (get_exact_entry(string(buf), data))
283  termlists.push_back(new GlassSpellingTermList(data));
284 
285  // Tail:
286  buf[0] = 'T';
287  buf[1] = word[word.size() - 2];
288  buf[2] = word[word.size() - 1];
289  if (get_exact_entry(string(buf), data))
290  termlists.push_back(new GlassSpellingTermList(data));
291 
292  if (word.size() <= 4) {
293  // We also generate 'bookends' for two, three, and four character
294  // terms so we can handle transposition of the middle two
295  // characters of a four character word, substitution or deletion of
296  // the middle character of a three character word, or insertion in
297  // the middle of a two character word.
298  buf[0] = 'B';
299  buf[1] = word[0];
300  buf[3] = '\0';
301  if (get_exact_entry(string(buf), data))
302  termlists.push_back(new GlassSpellingTermList(data));
303  }
304  if (word.size() > 2) {
305  // Middles:
306  buf[0] = 'M';
307  for (size_t start = 0; start <= word.size() - 3; ++start) {
308  memcpy(buf.data + 1, word.data() + start, 3);
309  if (get_exact_entry(string(buf), data))
310  termlists.push_back(new GlassSpellingTermList(data));
311  }
312 
313  if (word.size() == 3) {
314  // For three letter words, we generate the two "single
315  // transposition" forms too, so that we can produce good
316  // spelling suggestions.
317  // ABC -> BAC
318  buf[1] = word[1];
319  buf[2] = word[0];
320  if (get_exact_entry(string(buf), data))
321  termlists.push_back(new GlassSpellingTermList(data));
322  // ABC -> ACB
323  buf[1] = word[0];
324  buf[2] = word[2];
325  buf[3] = word[1];
326  if (get_exact_entry(string(buf), data))
327  termlists.push_back(new GlassSpellingTermList(data));
328  }
329  } else {
330  Assert(word.size() == 2);
331  // For two letter words, we generate H and T terms for the
332  // transposed form so that we can produce good spelling
333  // suggestions.
334  // AB -> BA
335  buf[0] = 'H';
336  buf[1] = word[1];
337  buf[2] = word[0];
338  if (get_exact_entry(string(buf), data))
339  termlists.push_back(new GlassSpellingTermList(data));
340  buf[0] = 'T';
341  if (get_exact_entry(string(buf), data))
342  termlists.push_back(new GlassSpellingTermList(data));
343  }
344 
345  return make_termlist_merger(termlists);
346  } catch (...) {
347  // Make sure we delete all the TermList objects to avoid leaking
348  // memory.
349  for (auto& t : termlists) {
350  delete t;
351  }
352  throw;
353  }
354 }
355 
358 {
359  auto i = wordfreq_changes.find(word);
360  if (i != wordfreq_changes.end()) {
361  // Modified frequency for word:
362  return i->second;
363  }
364 
365  string key = "W"s.append(word);
366  string data;
367  if (get_exact_entry(key, data)) {
368  // Word "word" already exists.
369  Xapian::termcount freq;
370  const char *p = data.data();
371  if (!unpack_uint_last(&p, p + data.size(), &freq)) {
372  throw Xapian::DatabaseCorruptError("Bad spelling word freq");
373  }
374  return freq;
375  }
376 
377  return 0;
378 }
379 
381 
384 {
385  // This is only used to decide how to build a OR-tree of TermList objects
386  // so we just need to return "sizes" which are ordered roughly correctly.
387  return clamp_cast<Xapian::termcount>(data.size());
388 }
389 
392 {
393  return 1;
394 }
395 
398 {
399  return 1;
400 }
401 
402 TermList *
404 {
405  if (p == data.size()) {
406  return this;
407  }
408  if (!current_term.empty()) {
409  current_term.resize(uint8_t(data[p++]) ^ MAGIC_XOR_VALUE);
410  }
411  size_t add;
412  if (p == data.size() ||
413  (add = uint8_t(data[p]) ^ MAGIC_XOR_VALUE) >= data.size() - p)
414  throw Xapian::DatabaseCorruptError("Bad spelling termlist");
415  current_term.append(data.data() + p + 1, add);
416  p += add + 1;
417  return NULL;
418 }
419 
420 TermList*
422 {
423  while (current_term < term) {
425  return this;
426  }
427  return NULL;
428 }
429 
432 {
433  throw Xapian::UnimplementedError("GlassSpellingTermList::positionlist_count() not implemented");
434 }
435 
438 {
439  throw Xapian::UnimplementedError("GlassSpellingTermList::positionlist_begin() not implemented");
440 }
#define MAGIC_XOR_VALUE
Cast a value to a type, clamping out of range values.
Xapian::termcount remove_word(std::string_view word, Xapian::termcount freqdec)
void merge_changes()
Merge in batched-up changes.
TermList * open_termlist(std::string_view word)
void toggle_fragment(Glass::fragment frag, std::string_view word)
void toggle_word(std::string_view word)
void add_word(std::string_view word, Xapian::termcount freqinc)
Xapian::doccount get_word_frequency(std::string_view word) const
The list of words containing a particular trigram.
Xapian::doccount get_termfreq() const
Return the term frequency for the term at the current position.
TermList * skip_to(std::string_view term)
Skip forward to the specified term.
Xapian::termcount positionlist_count() const
Return the length of the position list for the current position.
TermList * next()
Advance the current position to the next term in the termlist.
Xapian::termcount get_approx_size() const
Return approximate size of this termlist.
PositionList * positionlist_begin() const
Return PositionList for the current position.
Xapian::termcount get_wdf() const
Return the wdf for the term at the current position.
void append(const std::string &word)
DatabaseCorruptError indicates database corruption was detected.
Definition: error.h:397
Abstract base class for iterating term positions in a document.
Definition: positionlist.h:32
Abstract base class for termlists.
Definition: termlist.h:42
virtual Xapian::termcount get_approx_size() const =0
Return approximate size of this termlist.
UnimplementedError indicates an attempt to use an unimplemented feature.
Definition: error.h:313
string term
PositionList * p
Hierarchy of classes which Xapian can throw as exceptions.
Collate statistics and calculate the term weights for the ESet.
Spelling correction data for a glass database.
unsigned XAPIAN_TERMCOUNT_BASE_TYPE termcount
A counts of terms.
Definition: types.h:64
unsigned XAPIAN_DOCID_BASE_TYPE doccount
A count of documents.
Definition: types.h:37
Various assertion macros.
#define AssertRel(A, REL, B)
Definition: omassert.h:123
#define Assert(COND)
Definition: omassert.h:122
Pack types into strings and unpack them again.
bool unpack_uint_last(const char **p, const char *end, U *result)
Decode an unsigned integer as the last item in a string.
Definition: pack.h:118
void pack_uint_last(std::string &s, U value)
Append an encoded unsigned integer to a string as the last item.
Definition: pack.h:100
bool operator()(const TermList *a, const TermList *b) const
Build tree to merge TermList objects.
TermList * make_termlist_merger(std::vector< TermList * > &termlists)
typedefs for Xapian