rlucene 0.1.0-alpha.3

A Rust port of Apache Lucene, a full-text search engine library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
/*
 * 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.
 */
use crate::core::search::query::QueryRef;
use std::fmt::Write as _;

use crate::core::index::BytesRef;
use crate::core::index::bytes_ref::BytesRefValue;
use crate::core::index::doc_values_iterator::DocValuesIterator;
use crate::core::index::index_reader::Identity;
use crate::core::index::index_reader_context::{IRCLeafReader, IndexReaderContext};
use crate::core::index::leaf_reader::{LRNormNumericDocValues, LRPosting, LeafReader};
use crate::core::index::leaf_reader_context::LeafReaderContext;
use crate::core::index::numeric_doc_values::NumericDocValues;
use crate::core::index::postings_enum::{POSITIONS, PostingsEnum};
use crate::core::index::reader_util::ReaderUtil;
use crate::core::index::term::Term;
use crate::core::index::term_states::{TermStates, build, build_with_stats};
use crate::core::index::terms::Terms;
use crate::core::index::terms_enum::TermsEnum;
use crate::core::search::boolean_clause::Occur;
use crate::core::search::doc_id_set_iterator::DocIdSetIterator;
use crate::core::search::explanation::Explanation;
use crate::core::search::index_searcher::IndexSearcher;
use crate::core::search::match_no_docs_query::MatchNoDocsQuery;
use crate::core::search::multi_phrase_query;
use crate::core::search::phrase_query;
use crate::core::search::query::{Query, QueryBase};
use crate::core::search::query_visitor::QueryVisitor;
use crate::core::search::scorable::Scorable;
use crate::core::search::score_mode::ScoreMode;
use crate::core::search::segment_cacheable::SegmentCacheable;
use crate::core::search::similarities_impl::similarities::{
  SimScorer, Similarity, SimilaritySimScorer,
};
use crate::core::search::term_query::TermQuery;
use crate::core::search::term_statistics::TermStatistics;
use crate::core::search::weight::{DefaultScorerSupplier, Weight};
use crate::core::util::accountable::Accountable;
use crate::core::util::automation::automaton::{Automaton, Builder};
use crate::core::util::automation::operations::Operations;
use crate::core::util::automation::run_automaton::RunAutomaton;
use crate::core::util::automation::transition::Transition;
use crate::core::util::automation::transition_accessor::TransitionAccessor;
use crate::core::util::core_helper::HasIdentity;
use crate::core::util::error::lucene_error::{LuceneError, Result};
use crate::core::util::ram_usage_estimator::{size_of_hash_map, size_of_string, size_of_vec};
use crate::sandbox::search::term_automaton_scorer::{EnumAndScorer, TermAutomatonScorer};
#[cfg(test)]
use crate::test_framework::core::search::test_term_automaton_query::CustomTermAutomatonQuery;
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt::{Debug, Formatter};
use std::hash::{Hash, Hasher};
use std::sync::{Arc, OnceLock};

/// A proximity query that lets you express an automaton, whose transitions are terms, to match
/// documents. This is a generalization of other proximity queries like [`PhraseQuery`](crate::core::search::phrase_query::PhraseQuery),
/// [`MultiPhraseQuery`](crate::core::search::multi_phrase_query::MultiPhraseQuery) and `SpanNearQuery`. It is likely slow, since it visits any document having
/// any of the terms (i.e. it acts like a disjunction, not a conjunction like [`PhraseQuery`](crate::core::search::phrase_query::PhraseQuery)), and
/// then it must merge-sort all positions within each document to test whether/how many times the
/// automaton matches.
///
/// After creating the query, use `create_state`, `set_accept`, `add_transition` and
/// `add_any_transition` to build up the automaton. Once you are done, call `finish` and then execute
/// the query.
///
/// This code is very new and likely has exciting bugs!
///
/// Experimental: this API follows the original Lucene experimental status.
#[derive(Clone)]
pub struct TermAutomatonQuery {
  id: Identity,
  field: String,
  builder: Builder,
  det: Option<Automaton>,
  term_to_id: HashMap<Arc<[u8]>, i32>,
  id_to_term: Vec<Option<Arc<[u8]>>>,
  any_term_id: i32,
  hook: TermAutomatonQueryHook,
}

impl TermAutomatonQuery {
  pub fn new<T>(field: T) -> Self
  where
    T: Into<String>,
  {
    Self {
      id: Identity::new(),
      field: field.into(),
      builder: Builder::new(),
      det: None,
      term_to_id: HashMap::new(),
      id_to_term: Vec::new(),
      any_term_id: -1,
      hook: TermAutomatonQueryHook::Default(TermAutomatonQueryDefault),
    }
  }

  #[cfg(test)]
  pub(crate) fn with_hook<T>(field: T, hook: CustomTermAutomatonQuery) -> Self
  where
    T: Into<String>,
  {
    let mut query = Self::new(field);
    query.hook = TermAutomatonQueryHook::Custom(hook);
    query
  }

  /// Returns a new state; state 0 is always the initial state.
  pub fn create_state(&mut self) -> i32 {
    self.builder.create_state()
  }

  /// Marks the specified state as accept or not.
  pub fn set_accept(&mut self, state: i32, accept: bool) {
    self.builder.set_accept(state, accept);
  }

  /// Adds a transition to the automaton.
  pub fn add_transition(&mut self, source: i32, dest: i32, term: &str) -> Result<()> {
    let term_id = self.get_term_id(Some(term.as_bytes()))?;
    self.builder.add_transition_label(source, dest, term_id)
  }

  /// Adds a transition to the automaton.
  pub fn add_transition_bytes<T>(&mut self, source: i32, dest: i32, term: T) -> Result<()>
  where
    T: std::borrow::Borrow<BytesRef<Vec<u8>>>,
  {
    let term = term.borrow();
    let bytes = &term.bytes[term.offset..term.offset + term.length];
    let term_id = self.get_term_id(Some(bytes))?;
    self.builder.add_transition_label(source, dest, term_id)
  }

  /// Adds a transition matching any term.
  pub fn add_any_transition(&mut self, source: i32, dest: i32) -> Result<()> {
    let term_id = self.get_term_id(None)?;
    self.builder.add_transition_label(source, dest, term_id)
  }

  /// Call this once you are done adding states/transitions.
  pub fn finish(&mut self) -> Result<()> {
    self.finish_with_work_limit(Operations::DEFAULT_DETERMINIZE_WORK_LIMIT)
  }

  /// Call this once you are done adding states/transitions.
  ///
  /// `determinize_work_limit` is the maximum effort to spend determinizing the automaton. Higher
  /// numbers allow this operation to consume more memory but allow more complex automatons. Use
  /// [`Operations::DEFAULT_DETERMINIZE_WORK_LIMIT`](crate::core::util::automation::operations::Operations::DEFAULT_DETERMINIZE_WORK_LIMIT) as a decent default if you don't otherwise know
  /// what to specify.
  pub fn finish_with_work_limit(&mut self, determinize_work_limit: usize) -> Result<()> {
    let mut automaton = self.builder.finish()?;

    // println!("before det:\n{}", automaton.to_dot()?);

    let mut transition = Transition::default();

    if self.any_term_id != -1 {
      // Make sure there are no leading or trailing ANY:
      let count = automaton.init_transition(0, &mut transition);
      for _ in 0..count {
        automaton.get_next_transition(&mut transition)?;
        if self.any_term_id >= transition.min && self.any_term_id <= transition.max {
          return Err(LuceneError::illegal_state(
            "automaton cannot lead with an ANY transition",
          ));
        }
      }

      let num_states = automaton.get_num_states();
      for state in 0..num_states {
        let count = automaton.init_transition(state, &mut transition);
        for _ in 0..count {
          automaton.get_next_transition(&mut transition)?;
          if automaton.is_accept(transition.dest)
            && self.any_term_id >= transition.min
            && self.any_term_id <= transition.max
          {
            return Err(LuceneError::illegal_state(
              "automaton cannot end with an ANY transition",
            ));
          }
        }
      }

      let term_count = self.id_to_term.len() as i32;

      // We have to carefully translate these transitions so automaton
      // realizes they also match all other terms:
      let mut new_automaton = Automaton::new();
      for state in 0..num_states {
        new_automaton.create_state()?;
        new_automaton.set_accept(state, automaton.is_accept(state));
      }

      for state in 0..num_states {
        let count = automaton.init_transition(state, &mut transition);
        for _ in 0..count {
          automaton.get_next_transition(&mut transition)?;
          let (min, max) =
            if transition.min <= self.any_term_id && self.any_term_id <= transition.max {
              // Match any term
              (0, term_count - 1)
            } else {
              (transition.min, transition.max)
            };
          new_automaton.add_transition(transition.source, transition.dest, min, max)?;
        }
      }
      new_automaton.finish_state()?;
      automaton = new_automaton;
    }

    let deterministic = match Operations::determinize(&automaton, determinize_work_limit)? {
      Cow::Borrowed(_) => automaton,
      Cow::Owned(deterministic) => deterministic,
    };
    let det = match Operations::remove_dead_states(&deterministic)? {
      Cow::Borrowed(_) => deterministic,
      Cow::Owned(det) => det,
    };

    if det.is_accept(0) {
      return Err(LuceneError::illegal_state("cannot accept the empty string"));
    }
    self.det = Some(det);
    Ok(())
  }

  fn get_term_id(&mut self, term: Option<&[u8]>) -> Result<i32> {
    let Some(bytes) = term else {
      if self.any_term_id == -1 {
        self.any_term_id = self.id_to_term.len() as i32;
        self.id_to_term.push(None);
      }
      return Ok(self.any_term_id);
    };

    if let Some(id) = self.term_to_id.get(bytes) {
      return Ok(*id);
    }

    let id = self.id_to_term.len() as i32;
    let term: Arc<[u8]> = Arc::from(bytes);
    self.term_to_id.insert(Arc::clone(&term), id);
    self.id_to_term.push(Some(term));
    Ok(id)
  }

  fn check_finished(&self) {
    assert!(
      self.det.is_some(),
      "Call finish first on: {}",
      self
        .to_string(&self.field)
        .unwrap_or_else(|_| "TermAutomatonQuery".to_string())
    );
  }

  /// Returns the dot (graphviz) representation of this automaton. This is extremely useful for
  /// visualizing the automaton.
  pub fn to_dot(&self) -> Result<String> {
    let det = self
      .det
      .as_ref()
      .ok_or_else(|| LuceneError::illegal_state("call finish first"))?;
    let mut builder = String::new();
    builder.push_str("digraph Automaton {\n");
    builder.push_str("  rankdir = LR\n");
    let num_states = det.get_num_states();
    if num_states > 0 {
      builder.push_str("  initial [shape=plaintext,label=\"0\"]\n");
      builder.push_str("  initial -> 0\n");
    }

    let mut transition = Transition::default();
    for state in 0..num_states {
      builder.push_str("  ");
      write!(builder, "{}", state)?;
      if det.is_accept(state) {
        builder.push_str(" [shape=doublecircle,label=\"");
      } else {
        builder.push_str(" [shape=circle,label=\"");
      }
      write!(builder, "{}", state)?;
      builder.push_str("\"]\n");
      let count = det.init_transition(state, &mut transition);
      for _ in 0..count {
        det.get_next_transition(&mut transition)?;
        debug_assert!(transition.max >= transition.min);
        for term_id in transition.min..=transition.max {
          builder.push_str("  ");
          write!(builder, "{}", state)?;
          builder.push_str(" -> ");
          write!(builder, "{}", transition.dest)?;
          builder.push_str(" [label=\"");
          if term_id == self.any_term_id {
            builder.push('*');
          } else {
            let term = self.id_to_term[term_id as usize]
              .as_ref()
              .ok_or_else(|| LuceneError::illegal_state("term id has no term"))?;
            builder.push_str(
              BytesRef {
                bytes: term.as_ref(),
                offset: 0,
                length: term.len(),
              }
              .utf8_to_string()?,
            );
          }
          builder.push_str("\"]\n");
        }
      }
    }
    builder.push('}');
    Ok(builder)
  }
}

impl Debug for TermAutomatonQuery {
  fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
    match self.to_string("") {
      Ok(value) => formatter.write_str(&value),
      Err(_) => Err(std::fmt::Error),
    }
  }
}

impl HasIdentity for TermAutomatonQuery {
  fn identity(&self) -> &Identity {
    &self.id
  }
}

impl PartialEq for TermAutomatonQuery {
  fn eq(&self, other: &Self) -> bool {
    self.check_finished();
    other.check_finished();
    self.id == other.id
  }
}

impl Eq for TermAutomatonQuery {}

impl Hash for TermAutomatonQuery {
  fn hash<H: Hasher>(&self, state: &mut H) {
    self.check_finished();
    self.id.hash(state);
  }
}

impl Accountable for TermAutomatonQuery {
  fn ram_bytes_used(&self) -> Result<i64> {
    let mut size = self
      .id
      .ram_bytes_used()?
      .saturating_add(self.builder.ram_bytes_used()?)
      .saturating_add(size_of_string(&self.field))
      .saturating_add(size_of_hash_map(&self.term_to_id))
      .saturating_add(size_of_vec(&self.id_to_term));
    if let Some(det) = &self.det {
      size = size.saturating_add(det.ram_bytes_used()?);
    }
    for term in self.term_to_id.keys() {
      // Both tables retain the same Arc allocation, including its two reference counts.
      let allocation = (std::mem::size_of::<[std::sync::atomic::AtomicUsize; 2]>() + term.len())
        .next_multiple_of(std::mem::align_of::<std::sync::atomic::AtomicUsize>());
      size = size.saturating_add(allocation as i64);
    }
    Ok(size)
  }
}

pub trait TermAutomatonQueryBase {
  fn rewrite<IRC, SIM>(
    &self,
    query: &TermAutomatonQuery,
    searcher: &IndexSearcher<IRC, SIM>,
  ) -> Result<Option<Query>>
  where
    SIM: Similarity,
    IRC: IndexReaderContext + 'static,
    IndexSearcher<IRC, SIM>: Sync;
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) struct TermAutomatonQueryDefault;

impl TermAutomatonQueryBase for TermAutomatonQueryDefault {
  fn rewrite<IRC, SIM>(
    &self,
    query: &TermAutomatonQuery,
    searcher: &IndexSearcher<IRC, SIM>,
  ) -> Result<Option<Query>>
  where
    SIM: Similarity,
    IRC: IndexReaderContext + 'static,
    IndexSearcher<IRC, SIM>: Sync,
  {
    TermAutomatonQueryDefaults::rewrite(query, searcher)
  }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum TermAutomatonQueryHook {
  Default(TermAutomatonQueryDefault),
  #[cfg(test)]
  Custom(CustomTermAutomatonQuery),
}

impl TermAutomatonQueryBase for TermAutomatonQueryHook {
  fn rewrite<IRC, SIM>(
    &self,
    query: &TermAutomatonQuery,
    searcher: &IndexSearcher<IRC, SIM>,
  ) -> Result<Option<Query>>
  where
    SIM: Similarity,
    IRC: IndexReaderContext + 'static,
    IndexSearcher<IRC, SIM>: Sync,
  {
    match self {
      Self::Default(hook) => hook.rewrite(query, searcher),
      #[cfg(test)]
      Self::Custom(hook) => hook.rewrite(query, searcher),
    }
  }
}

pub struct TermAutomatonQueryDefaults;

impl TermAutomatonQueryDefaults {
  pub fn rewrite<IRC, SIM>(
    query: &TermAutomatonQuery,
    _searcher: &IndexSearcher<IRC, SIM>,
  ) -> Result<Option<Query>>
  where
    SIM: Similarity,
    IRC: IndexReaderContext + 'static,
    IndexSearcher<IRC, SIM>: Sync,
  {
    let det = query
      .det
      .as_ref()
      .ok_or_else(|| LuceneError::illegal_state("Call finish first"))?;
    if Operations::is_empty(det)? {
      return Ok(Some(MatchNoDocsQuery::new().into()));
    }

    if let Some(single) = Operations::get_singleton(det)?
      && single.length == 1
    {
      let term_id = single.ints[single.offset] as usize;
      let term = query.id_to_term[term_id]
        .as_ref()
        .ok_or_else(|| LuceneError::illegal_state("singleton term is ANY"))?;
      return Ok(Some(
        TermQuery::new(Term::new(query.field.clone(), term.as_ref())).into(),
      ));
    }

    // Try for either PhraseQuery or MultiPhraseQuery, which only works when the automaton is a
    // sausage:
    let mut multi_phrase_builder = Some(multi_phrase_query::Builder::new());
    let mut phrase_builder = Some(phrase_query::Builder::new());

    let mut transition = Transition::default();
    let mut state = 0;
    let mut position = 0;
    let mut ranges = Vec::new();
    let mut terms = Vec::new();
    'query: loop {
      let count = det.init_transition(state, &mut transition);
      if count == 0 {
        if !det.is_accept(state) {
          multi_phrase_builder = None;
          phrase_builder = None;
        }
        break;
      } else if det.is_accept(state) {
        multi_phrase_builder = None;
        phrase_builder = None;
        break;
      }
      let mut dest = -1;
      ranges.clear();
      let mut matches_any = false;
      for transition_index in 0..count {
        det.get_next_transition(&mut transition)?;
        if transition_index == 0 {
          dest = transition.dest;
        } else if dest != transition.dest {
          multi_phrase_builder = None;
          phrase_builder = None;
          break 'query;
        }

        matches_any |= query.any_term_id >= transition.min && query.any_term_id <= transition.max;
        ranges.push((transition.min, transition.max));
      }
      if !matches_any {
        for (min, max) in ranges.drain(..) {
          for term_id in min..=max {
            let bytes = query.id_to_term[term_id as usize]
              .as_ref()
              .ok_or_else(|| LuceneError::illegal_state("term id has no term"))?;
            terms.push(Term::new(query.field.clone(), bytes.as_ref()));
          }
        }
        multi_phrase_builder
          .as_mut()
          .ok_or_else(|| LuceneError::illegal_state("multi-phrase builder is missing"))?
          .add_terms_with_position(&terms, position)?;
        if let Some(builder) = &mut phrase_builder {
          if terms.len() == 1 {
            builder.add(terms.remove(0), position as usize)?;
          } else {
            phrase_builder = None;
          }
        }
        terms.clear();
      }
      state = dest;
      position += 1;
    }

    if let Some(builder) = phrase_builder {
      return Ok(Some(builder.build()?.into()));
    }
    if let Some(builder) = multi_phrase_builder {
      return Ok(Some(builder.build().into()));
    }

    Ok(None)
  }
}

impl QueryBase for TermAutomatonQuery {
  type Weight<IRC, SIM>
    = TermAutomatonWeight<SIM>
  where
    SIM: Similarity,
    IRC: IndexReaderContext + 'static;

  fn to_string(&self, _field: &str) -> Result<String> {
    let mut value = format!("TermAutomatonQuery(field={}", self.field);
    if let Some(det) = &self.det {
      value.push_str(" numStates=");
      write!(value, "{}", det.get_num_states())?;
    }
    value.push(')');
    Ok(value)
  }

  fn create_weight<IRC, SIM>(
    self,
    searcher: &IndexSearcher<IRC, SIM>,
    score_mode: &ScoreMode,
    boost: f32,
  ) -> Result<Self::Weight<IRC, SIM>>
  where
    SIM: Similarity,
    IRC: IndexReaderContext + 'static,
    IndexSearcher<IRC, SIM>: Sync,
  {
    TermAutomatonWeight::new(self, searcher, score_mode, boost)
  }

  fn rewrite<IRC, SIM>(&self, searcher: &IndexSearcher<IRC, SIM>) -> Result<Option<Query>>
  where
    SIM: Similarity,
    IRC: IndexReaderContext + 'static,
    IndexSearcher<IRC, SIM>: Sync,
  {
    self.hook.rewrite(self, searcher)
  }

  fn visit<QV>(&self, visitor: &mut QV) -> Result<()>
  where
    QV: QueryVisitor,
  {
    if !visitor.accept_field(&self.field) {
      return Ok(());
    }
    let query = self.into();
    let mut visitor = visitor.get_sub_visitor(Occur::Should, query);
    let terms = self
      .id_to_term
      .iter()
      .flatten()
      .map(|term| Term::new(self.field.clone(), term.as_ref()))
      .collect::<Vec<_>>();
    visitor.consume_terms(query, &terms)
  }
}

pub struct TermAutomatonWeight<
  SIM = crate::core::search::similarities_impl::bm25_similarity::BM25Similarity,
> where
  SIM: Similarity,
{
  term_states: Vec<Option<TermStates>>,
  stats: Option<Arc<SimilaritySimScorer<SIM>>>,
  parent_query: TermAutomatonQuery,
  run_automaton: OnceLock<RunAutomaton>,
}

impl<SIM> Debug for TermAutomatonWeight<SIM>
where
  SIM: Similarity,
{
  fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
    match self.parent_query.to_string("") {
      Ok(value) => write!(formatter, "weight({value})"),
      Err(_) => Err(std::fmt::Error),
    }
  }
}

impl<SIM> TermAutomatonWeight<SIM>
where
  SIM: Similarity,
{
  fn new<IRC>(
    query: TermAutomatonQuery,
    searcher: &IndexSearcher<IRC, SIM>,
    score_mode: &ScoreMode,
    boost: f32,
  ) -> Result<Self>
  where
    IRC: IndexReaderContext + 'static,
    IndexSearcher<IRC, SIM>: Sync,
  {
    query
      .det
      .as_ref()
      .ok_or_else(|| LuceneError::illegal_state("Call finish first"))?;
    let mut term_states = Vec::with_capacity(query.id_to_term.len());
    let mut all_term_stats =
      smallvec::SmallVec::<[TermStatistics; 8]>::with_capacity(query.id_to_term.len());
    for term in &query.id_to_term {
      if let Some(term) = term {
        let index_term = Arc::new(Term::new(query.field.clone(), term.as_ref()));
        let states = if score_mode.needs_scores() {
          build_with_stats(searcher, &index_term)?
        } else {
          build(searcher, index_term.clone(), false)?
        };
        if states.doc_freq()? > 0 {
          all_term_stats.push(searcher.term_statistics(
            index_term,
            states.doc_freq()?,
            states.total_term_freq()?,
          )?);
        }
        term_states.push(Some(states));
      } else {
        term_states.push(None);
      }
    }

    let similarity = searcher.similarity();
    let stats = if all_term_stats.is_empty() {
      None // no terms matched at all, will not use sim
    } else {
      let collection_stats = searcher
        .collection_statistics(&query.field)?
        .ok_or_else(|| LuceneError::illegal_state("collection statistics are missing"))?;
      Some(Arc::new(similarity.scorer(
        boost,
        &collection_stats,
        &all_term_stats,
      )?))
    };

    Ok(Self {
      term_states,
      stats,
      parent_query: query,
      run_automaton: OnceLock::new(),
    })
  }

  fn query(&self) -> Result<&TermAutomatonQuery> {
    Ok(&self.parent_query)
  }

  #[allow(clippy::type_complexity)] // Preserve the concrete generic scorer types without erasure.
  fn build_scorer<LR>(
    &self,
    context: &LeafReaderContext<LR>,
  ) -> Result<
    Option<
      TermAutomatonScorer<LRPosting<LR>, SimilaritySimScorer<SIM>, LRNormNumericDocValues<LR>>,
    >,
  >
  where
    LR: LeafReader,
  {
    let query = self.query()?;
    let field_terms = match context.reader().terms(&query.field)? {
      Some(terms) => terms,
      None => return Ok(None),
    };
    let mut subs = Vec::new();
    for (term_id, states) in self.term_states.iter().enumerate() {
      let Some(states) = states else {
        continue;
      };
      debug_assert!(
        states.was_built_for(ReaderUtil::get_top_level_context(context)),
        "The top-reader used to create Weight is not the same as the current reader's top-reader"
      );
      let mut supplier = states.get(context)?;
      let state = match supplier {
        Some(ref mut supplier) => states.resolve(supplier)?,
        None => None,
      };
      let Some(state) = state else {
        continue;
      };
      let term = query.id_to_term[term_id]
        .as_ref()
        .ok_or_else(|| LuceneError::illegal_state("term states exist for ANY"))?;
      let mut terms_enum = field_terms.iterator()?;
      terms_enum.seek_exact_with_state(
        &BytesRef {
          bytes: term.as_ref(),
          offset: 0,
          length: term.len(),
        },
        state.as_ref(),
      )?;
      subs.push(EnumAndScorer::new(
        term_id as i32,
        terms_enum.postings_with_flags(None, POSITIONS as i32)?,
      ));
    }

    if subs.is_empty() {
      return Ok(None);
    }
    let norms = context.reader().get_norm_values(&query.field)?;
    let stats = self
      .stats
      .as_ref()
      .ok_or_else(|| LuceneError::illegal_state("similarity scorer is missing"))?
      .clone();
    let run_automaton = if let Some(compiled) = self.run_automaton.get() {
      compiled.clone()
    } else {
      let compiled = RunAutomaton::new(
        query
          .det
          .as_ref()
          .ok_or_else(|| LuceneError::illegal_state("Call finish first"))?
          .clone(),
        query.id_to_term.len(),
      )?;
      self.run_automaton.get_or_init(|| compiled).clone()
    };
    Ok(Some(TermAutomatonScorer::new(
      run_automaton,
      subs,
      query.any_term_id,
      stats,
      norms,
    )?))
  }
}

impl<IRC, SIM> SegmentCacheable<IRC> for TermAutomatonWeight<SIM>
where
  SIM: Similarity,
  IRC: IndexReaderContext + 'static,
{
  fn is_cacheable(&self, _ctx: &LeafReaderContext<IRCLeafReader<IRC>>) -> Result<bool> {
    Ok(true)
  }
}

impl<IRC, SIM> Weight<IRC, SIM> for TermAutomatonWeight<SIM>
where
  SIM: Similarity,
  IRC: IndexReaderContext + 'static,
{
  fn explain(
    &self,
    context: &LeafReaderContext<IRCLeafReader<IRC>>,
    doc: i32,
    _searcher: &IndexSearcher<IRC, SIM>,
  ) -> Result<Explanation>
  where
    IndexSearcher<IRC, SIM>: Sync,
  {
    let Some(mut scorer) = self.build_scorer(context)? else {
      return Ok(Explanation::no_match_no_details(
        "No matching terms in the document",
      ));
    };

    let advanced_doc = scorer.advance(doc)?;
    if advanced_doc != doc {
      return Ok(Explanation::no_match_no_details(
        "No matching terms in the document",
      ));
    }

    let score = scorer.score()?;
    let query = self.query()?;

    let mut norms = context.reader().get_norm_values(&query.field)?;
    let mut norm = 1i64;
    if let Some(norms) = &mut norms
      && norms.advance_exact(doc)?
    {
      norm = norms.long_value()?;
    }

    let stats = self
      .stats
      .as_ref()
      .ok_or_else(|| LuceneError::illegal_state("similarity scorer is missing"))?;
    let original_subs_on_doc = scorer.original_subs_on_doc();
    let mut term_explanations = Vec::with_capacity(original_subs_on_doc.len());
    for sub in original_subs_on_doc {
      if sub.pos_enum.doc_id() == doc {
        let frequency = sub.pos_enum.freq()?;
        let term_score = stats.score(frequency as f32, norm);
        let term = query.id_to_term[sub.term_id as usize]
          .as_ref()
          .ok_or_else(|| LuceneError::illegal_state("term id has no term"))?;
        term_explanations.push(Explanation::match_(
          frequency,
          "term frequency in the document",
          vec![Explanation::match_no_details(
            term_score,
            format!(
              "score for term: {}",
              BytesRef {
                bytes: term.as_ref(),
                offset: 0,
                length: term.len(),
              }
              .utf8_to_string()?
            ),
          )],
        ));
      }
    }

    if term_explanations.is_empty() {
      return Ok(Explanation::no_match_no_details(
        "No matching terms in the document",
      ));
    }

    let freq_explanation =
      Explanation::match_(score, "TermAutomatonQuery, sum of:", term_explanations);
    stats.explain(freq_explanation, norm)
  }

  fn get_query(&self) -> QueryRef<'_> {
    QueryRef::TermAutomaton(&self.parent_query)
  }

  type ScorerSupplier = DefaultScorerSupplier<
    TermAutomatonScorer<
      LRPosting<IRCLeafReader<IRC>>,
      SimilaritySimScorer<SIM>,
      LRNormNumericDocValues<IRCLeafReader<IRC>>,
    >,
  >;

  fn scorer_supplier(
    &self,
    context: &LeafReaderContext<IRCLeafReader<IRC>>,
    _searcher: &IndexSearcher<IRC, SIM>,
  ) -> Result<Option<Self::ScorerSupplier>>
  where
    IndexSearcher<IRC, SIM>: Sync,
  {
    let Some(scorer) = self.build_scorer(context)? else {
      return Ok(None);
    };
    Ok(Some(DefaultScorerSupplier::new(scorer)))
  }
}