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
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
//! Query parsing and resolving.
//!
//! This handles AND, OR, and NOT operations, as well as parentheses which are resolved before the
//! others.

use std::borrow::Borrow;
use std::collections::BTreeSet;
use std::fmt::{self, Debug, Display};
use std::iter::Peekable;

use crate::index::{self, AssociatedOccurrence};
use crate::index::{Occurence, Provider};
use crate::proximity::ProximateMap;
use crate::{proximity, set};
use iter_set::Inclusion;
pub use parse::{parse, Options as ParseOptions};

#[derive(Debug, Clone)]
#[must_use]
/// Eq implementation doesn't care of which is left and right.
pub struct BinaryPart {
    pub left: Part,
    pub right: Part,
}
impl BinaryPart {
    pub fn new(left: Part, right: Part) -> Self {
        Self { left, right }
    }
    #[must_use]
    pub fn into_box(self) -> Box<Self> {
        Box::new(self)
    }
    /// Swaps [`Self::left`] and [`Self::right`].
    ///
    /// This does not affect [`Eq`].
    pub fn swap(&mut self) {
        std::mem::swap(&mut self.left, &mut self.right);
    }
    /// Tests the equality of the parts AND order of [`Self::left`] & [`Self::right`].
    #[must_use]
    pub fn eq_order(&self, other: &Self) -> bool {
        self.left.eq_order(&other.left) && self.right.eq_order(&other.right)
    }
}
impl PartialEq for BinaryPart {
    fn eq(&self, other: &Self) -> bool {
        (self.left == other.left && self.right == other.right)
            || (self.left == other.right && self.right == other.left)
    }
}
impl Eq for BinaryPart {}

/// A part of a [`Query`].
#[derive(PartialEq, Eq, Clone)]
#[must_use]
pub enum Part {
    And(Box<BinaryPart>),
    Or(Box<BinaryPart>),
    Not(Box<Part>),

    String(String),
}
impl Part {
    pub fn s(s: impl AsRef<str>) -> Self {
        Self::String(s.as_ref().into())
    }
    pub fn and(left: impl Into<Self>, right: impl Into<Self>) -> Self {
        Self::And(BinaryPart::new(left.into(), right.into()).into_box())
    }
    pub fn or(left: impl Into<Self>, right: impl Into<Self>) -> Self {
        Self::Or(BinaryPart::new(left.into(), right.into()).into_box())
    }
    pub fn not(not: impl Into<Self>) -> Self {
        Self::Not(Box::new(not.into()))
    }

    pub fn for_each<'a>(&'a self, f: &mut impl FnMut(&'a Part)) {
        f(self);
        match self {
            Self::And(pair) | Self::Or(pair) => {
                pair.left.for_each(f);
                pair.right.for_each(f);
            }
            Self::Not(not) => not.for_each(f),
            Self::String(_s) => {}
        }
    }
    pub fn for_each_string<'a>(&'a self, f: &mut impl FnMut(&'a str)) {
        match self {
            Self::And(pair) | Self::Or(pair) => {
                pair.left.for_each_string(f);
                pair.right.for_each_string(f);
            }
            Self::Not(not) => not.for_each_string(f),
            Self::String(s) => f(s),
        }
    }

    /// Tests the equality of the parts AND order.
    ///
    /// See [`BinaryPart`] for more details.
    ///
    /// This makes no difference to the [`Eq`] implementation if `self` is [`Self::Not`] or
    /// [`Self::String`].
    #[must_use]
    pub fn eq_order(&self, other: &Self) -> bool {
        if !self.eq(other) {
            return false;
        }
        match self {
            Self::String(_) | Self::Not(_) => true,
            Self::Or(p1) | Self::And(p1) => {
                if let Self::Or(p2) | Self::And(p2) = other {
                    p1.eq_order(p2)
                } else {
                    false
                }
            }
        }
    }
    /// Casts a generic [`Iterator`] to a [`dyn`](https://doc.rust-lang.org/std/keyword.dyn.html) one.
    ///
    /// This is a convenience function as the cast is hard inline.
    fn iter_to_box<'a, T>(iter: impl Iterator<Item = T> + 'a) -> Box<dyn Iterator<Item = T> + 'a> {
        Box::new(iter)
    }
    #[allow(clippy::type_complexity)]
    fn fn_to_box<'a, T>(
        f: impl FnMut(&'a str) -> Option<Box<dyn Iterator<Item = T> + 'a>> + 'a,
    ) -> Box<(dyn FnMut(&'a str) -> Option<Box<dyn Iterator<Item = T> + 'a>> + 'a)> {
        Box::new(f)
    }
    fn as_doc_iter<
        'a,
        'b,
        T: Ord + 'a,
        AndMI: Iterator<Item = T> + 'a,
        OrMI: Iterator<Item = T> + 'a,
    >(
        &'a self,
        mut iter: impl std::ops::DerefMut<
                Target = (impl FnMut(&'a str) -> Option<Box<dyn Iterator<Item = T> + 'a>> + ?Sized + 'a),
            > + 'b,
        and_not_modify: &impl Fn(
            Box<dyn Iterator<Item = T> + 'a>,
            Box<dyn Iterator<Item = T> + 'a>,
        ) -> Box<dyn Iterator<Item = T> + 'a>,
        and_merger: &impl Fn(
            Box<dyn Iterator<Item = T> + 'a>,
            Box<dyn Iterator<Item = T> + 'a>,
        ) -> AndMI,
        or_merger: &impl Fn(Box<dyn Iterator<Item = T> + 'a>, Box<dyn Iterator<Item = T> + 'a>) -> OrMI,
    ) -> Result<Box<dyn Iterator<Item = T> + 'a>, IterError> {
        let iter = match self {
            Self::And(pair) => match (&pair.left, &pair.right) {
                (other, Part::Not(not)) | (Part::Not(not), other) => and_not_modify(
                    other.as_doc_iter(&mut *iter, and_not_modify, and_merger, or_merger)?,
                    not.as_doc_iter(&mut *iter, and_not_modify, and_merger, or_merger)?,
                ),
                _ => Self::iter_to_box(and_merger(
                    pair.left
                        .as_doc_iter(&mut *iter, and_not_modify, and_merger, or_merger)?,
                    pair.right
                        .as_doc_iter(&mut *iter, and_not_modify, and_merger, or_merger)?,
                )),
            },
            Self::Or(pair) => Self::iter_to_box(or_merger(
                pair.left
                    .as_doc_iter(&mut *iter, and_not_modify, and_merger, or_merger)?,
                pair.right
                    .as_doc_iter(&mut *iter, and_not_modify, and_merger, or_merger)?,
            )),
            Self::Not(_) => return Err(IterError::StrayNot),
            Self::String(s) => {
                iter(s).map_or_else(|| Self::iter_to_box(std::iter::empty()), Self::iter_to_box)
            }
        };
        Ok(iter)
    }
}
impl<T: Into<String>> From<T> for Part {
    fn from(s: T) -> Self {
        Self::String(s.into())
    }
}
impl Debug for Part {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Display::fmt(self, f)
    }
}
impl Display for Part {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fn fmt_pair(f: &mut fmt::Formatter<'_>, pair: &BinaryPart, op: &str) -> fmt::Result {
            write!(f, "({} {} {})", pair.left, op, pair.right)
        }
        match self {
            Self::String(s) => f.write_str(s),
            Self::And(pair) => fmt_pair(f, pair, "AND"),
            Self::Or(pair) => fmt_pair(f, pair, "OR"),
            Self::Not(not) => write!(f, "(NOT {})", not),
        }
    }
}

/// An iterator of documents which matches a [`Query`].
#[derive(Debug)]
pub struct Documents<'a, 'b, P: Provider<'a>> {
    proximate_map: ProximateMap<'b>,
    query: &'b Query,
    provider: &'a P,
}
impl<'a, 'b, P: Provider<'a>> Documents<'a, 'b, P> {
    /// # Errors
    ///
    /// If a [`Part::Not`] isn't associated with a [`Part::And`], [`IterError::StrayNot`] is
    /// returned.
    ///
    /// This is due to a limitation of the index architecture used by this library,
    /// and almost all other search engines.
    #[allow(clippy::iter_not_returning_iterator)] // it does, within a result
    pub fn iter(&'a self) -> Result<impl Iterator<Item = index::Id> + 'a, IterError> {
        self.query.root().as_doc_iter(
            if let proximity::Algorithm::Exact = self.provider.word_proximity_algorithm() {
                Part::fn_to_box(|s| self.provider.documents_with_word(s).map(Part::iter_to_box))
            } else {
                Part::fn_to_box(|s| {
                    let list = self.proximate_map.get_or_panic(s);
                    Some(Part::iter_to_box(
                        crate::proximity::proximate_word_docs(self.provider, list)
                            .map(|item| item.id)
                            .collect::<BTreeSet<_>>()
                            .into_iter(),
                    ))
                })
            },
            &|i, _| i,
            &set::intersect,
            &set::union,
        )
    }
    /// The list of proximate words.
    /// This is populated on creation and used in [`Self::iter`].
    /// Using [`Self::iter`] after calling this will most likely result in a panic.
    pub fn take_proximate_map(&mut self) -> ProximateMap<'b> {
        core::mem::take(&mut self.proximate_map)
    }
}

/// A query.
///
/// This is just a root [`Part`].
///
/// Use [`mod@parse`] to create one.
/// You can also use the [`std::str::FromStr`] implementation.
#[derive(Debug, PartialEq, Eq, Clone)]
#[must_use]
pub struct Query {
    root: Part,
}
impl Query {
    fn new(root: Part) -> Self {
        Self { root }
    }
    /// Get a reference to the root node of the query.
    pub fn root(&self) -> &Part {
        &self.root
    }
    pub fn documents<'a, 'b, P: Provider<'a>>(&'b self, provider: &'a P) -> Documents<'a, 'b, P> {
        let mut proximate_map = proximity::ProximateMap::new();
        if let proximity::Algorithm::Exact = provider.word_proximity_algorithm() {
            // Do nothing, it doesn't read this.
        } else {
            self.root().for_each_string(&mut |s| {
                proximity::proximate_words(s, provider).extend_proximates(&mut proximate_map);
            });
        }
        Documents {
            proximate_map,
            query: self,
            provider,
        }
    }
    /// The `distance_threshold` is the bytes between two occurrences to consider the "same", which
    /// increases [`Hit::rating`].
    ///
    /// # Errors
    ///
    /// See [`Self::documents`].
    ///
    /// # Panics
    ///
    /// Some implementations of [`index::OccurenceProvider`] panic under certain circumstances.
    ///
    /// [`index::SimpleOccurences`], for example, panics if you haven't supplied all the necessary
    /// documents.
    #[allow(clippy::too_many_lines)]
    pub fn occurrences<'a>(
        &'a self,
        provider: &'a impl index::OccurenceProvider<'a>,
        distance_threshold: usize,
    ) -> Result<impl Iterator<Item = Hit> + 'a, IterError> {
        #[derive(Debug, Clone)]
        struct OccurenceEq(Hit);
        impl OccurenceEq {
            #[inline]
            fn new(mut occ: Occurence, word_id: u32) -> Self {
                occ.word_id = word_id;
                Self(Hit::new(occ))
            }
            #[must_use]
            fn closest(&self, other: &Self) -> (usize, AssociatedOccurrence) {
                use std::cmp::Ordering;
                let mut closest = (usize::MAX, AssociatedOccurrence::new(0, 0));
                let mut a_iter = self.0.occurrences();
                // If `associated_occurrences` has len 0, use only start.
                // Else, it'll have >=2 occurences, since the `.start()` is also taken as part of
                // the BTreeSet.
                let mut a = a_iter.next().unwrap_or_else(|| (&self.0).into());
                let mut a_start = a.start();
                let mut b_iter = other.0.occurrences();
                let mut b = b_iter.next().unwrap_or_else(|| (&other.0).into());
                let mut b_start = b.start();
                let mut one_completed = false;
                loop {
                    let dist = if a_start > b_start {
                        a_start - b_start
                    } else {
                        b_start - a_start
                    };
                    closest = std::cmp::min_by((dist, b), closest, |a, b| a.0.cmp(&b.0));
                    match a.cmp(&b) {
                        Ordering::Less => {
                            if let Some(next) = a_iter.next() {
                                a = next;
                                a_start = a.start();
                            } else if one_completed {
                                break;
                            } else {
                                one_completed = true;
                            }
                        }
                        // The words are at the same place!
                        //
                        // This is technically not reachable, but the following codes makes sense.
                        Ordering::Equal => return (0, b),
                        Ordering::Greater => {
                            if let Some(next) = b_iter.next() {
                                b = next;
                                b_start = b.start();
                            } else if one_completed {
                                break;
                            } else {
                                one_completed = true;
                            }
                        }
                    }
                }
                closest
            }
        }
        impl PartialEq for OccurenceEq {
            #[inline]
            fn eq(&self, other: &Self) -> bool {
                self.0.id().eq(&other.0.id())
            }
        }
        impl Eq for OccurenceEq {}
        impl Ord for OccurenceEq {
            #[inline]
            fn cmp(&self, other: &Self) -> std::cmp::Ordering {
                self.0.id().cmp(&other.0.id())
            }
        }
        impl PartialOrd for OccurenceEq {
            #[inline]
            fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
                Some(self.cmp(other))
            }
        }
        impl Borrow<index::Id> for OccurenceEq {
            #[inline]
            fn borrow(&self) -> &index::Id {
                &self.0.occurrence.document_id
            }
        }

        #[derive(Debug)]
        struct MergeProximate<I>
        where
            I: Iterator<Item = OccurenceEq>,
        {
            iter: Peekable<I>,
            distance_threshold: usize,
        }
        impl<I: Iterator<Item = OccurenceEq>> MergeProximate<I> {
            fn new(iter: I, distance_threshold: usize) -> Self {
                Self {
                    iter: iter.peekable(),
                    distance_threshold,
                }
            }
        }
        impl<I: Iterator<Item = OccurenceEq>> Iterator for MergeProximate<I> {
            type Item = OccurenceEq;
            fn next(&mut self) -> Option<Self::Item> {
                let mut next = self.iter.next()?;

                let peeked = match self.iter.peek() {
                    Some(peeked) => peeked,
                    None => return Some(next),
                };

                if peeked.0.id() != next.0.id() {
                    return Some(next);
                }

                // `TODO`: Similar words won't get merged - they come sequentially.
                let dist = if peeked.0.start() < next.0.start() {
                    next.0.start() - peeked.0.start()
                } else {
                    peeked.0.start() - next.0.start()
                };
                if dist > self.distance_threshold {
                    return Some(next);
                }
                *next.0.rating_mut() += 2.0;
                next.0.merge(&peeked.0);
                drop(self.next());
                Some(next)
            }
        }

        #[inline]
        fn abs_diff_occurrence(a: &OccurenceEq, b: &OccurenceEq) -> usize {
            a.0.start().abs_diff(b.0.start())
        }

        let mut word_id: u32 = 0;
        self.root()
            .as_doc_iter(
                &mut move |s| {
                    // Logic error if we wrap, but we'd need more than 4M words, and it only
                    // results in marginally worse relevance for search results and context.
                    word_id = word_id.wrapping_add(1);
                    provider.occurrences_of_word(s).map(move |iter| {
                        Part::iter_to_box(MergeProximate::new(
                            iter.map(
                                #[inline]
                                move |hit| OccurenceEq::new(hit, word_id),
                            ),
                            distance_threshold,
                        ))
                    })
                },
                &|and, not| {
                    Part::iter_to_box(
                        crate::set::progressive(
                            and,
                            not,
                            #[inline]
                            |and, not| and.0.start().cmp(&not.0.start()),
                            std::cmp::Ord::cmp,
                            Some(abs_diff_occurrence),
                        )
                        .filter_map(|inclusion| match inclusion {
                            Inclusion::Left(mut and) => {
                                *and.0.rating_mut() += 2.5;
                                Some(and)
                            }
                            Inclusion::Right(_not) => None,
                            Inclusion::Both(mut and, not) => {
                                let not_rating = not.0.rating();
                                let closest = and.closest(&OccurenceEq::new(not.0.occurrence, 0));
                                // Don't really care about precision.
                                #[allow(clippy::cast_precision_loss)]
                                let rating_decrease = 1.0 / (0.0001 * closest.0 as f32 + 0.025);
                                *and.0.rating_mut() -= rating_decrease;
                                // by decreasing the rating based on the not rating too, we remove
                                // extra when there are multiple NOTs.
                                // `TODO` apply the same filter as we do below for acceted ones for
                                // the NOT occurrences, so groups are better recognized.
                                *and.0.rating_mut() -= not_rating;
                                and.0.closest_not = Some(closest.1);
                                Some(and)
                            }
                        }),
                    )
                },
                // AND merger
                &|left, right| {
                    crate::set::progressive(
                        left,
                        right,
                        #[inline]
                        |a, b| a.0.start().cmp(&b.0.start()),
                        // Compares IDs
                        #[inline]
                        |a, b| (*a).cmp(b),
                        None,
                    )
                    .filter_map(|inclusion| match inclusion {
                        Inclusion::Both(mut a, b) => {
                            a.0.merge(&b.0);
                            Some(a)
                        }
                        _ => None,
                    })
                },
                // OR merger
                &|left, right| {
                    crate::set::progressive(
                        left,
                        right,
                        #[inline]
                        |a, b| a.0.start().cmp(&b.0.start()),
                        // Compares IDs
                        #[inline]
                        |a, b| (*a).cmp(b),
                        None,
                    )
                    .map(|inclusion| match inclusion {
                        Inclusion::Both(mut a, b) => {
                            a.0.merge(&b.0);
                            a
                        }
                        Inclusion::Left(a) | Inclusion::Right(a) => a,
                    })
                },
            )
            .map(|iter| {
                iter.map(|occ| {
                    let mut occ = occ.0;

                    let mut increase = 0.;
                    // We keep track of the closest to determine which index should be the `major`
                    // one.
                    let (mut closest, mut closest_index) = (usize::MAX, 0);

                    let mut iter = occ.occurrences();
                    let mut last = iter
                        .next()
                        .unwrap_or_else(|| AssociatedOccurrence::new(0, 0));

                    for (idx, associated_occ) in iter.enumerate() {
                        if last.word_id() != associated_occ.word_id() {
                            let dist = associated_occ.start() - last.start();
                            if dist < closest {
                                closest_index = idx;
                            }
                            closest = std::cmp::min(dist, closest);
                            // Don't really care about precision.
                            #[allow(clippy::cast_precision_loss)]
                            let rating_increase = 0.5 / (0.001 * dist as f32 + 0.1);
                            increase += rating_increase;
                        }
                        last = associated_occ;
                    }
                    *occ.rating_mut() += increase;

                    // replace `occurrence.start()` with the closest match.
                    // This requires removing the closest from the set and setting as "main"
                    // and inserting "main" to the set.
                    if closest_index != 0 {
                        let closest = occ.occurrences().nth(closest_index).unwrap();
                        occ.occurrences.remove(&closest);
                        occ.occurrences.insert((&occ.occurrence).into());
                        *occ.occurrence.start_mut() = closest.start();
                    }

                    occ
                })
            })
    }
}

/// An occurrence returned from [`Query`].
#[derive(Debug, Clone)]
pub struct Hit {
    occurrence: Occurence,

    /// [`Self::occurrence`] (if [`Self::merged`]) and all associated occurrences.
    occurrences: BTreeSet<AssociatedOccurrence>,
    /// If we have been merged. Used to tell if `self.occurrence.start()` is in the occurrences
    /// BTree. We don't do this by default to avoid an allocation.
    merged: bool,

    closest_not: Option<AssociatedOccurrence>,
}
impl Hit {
    #[inline]
    fn new(occurrence: Occurence) -> Self {
        Self {
            occurrence,
            occurrences: BTreeSet::new(),
            merged: false,
            closest_not: None,
        }
    }
    /// Get a reference to the hit's document id.
    #[must_use]
    #[inline]
    pub fn id(&self) -> index::Id {
        self.occurrence.id()
    }
    /// Get a reference to the hit's word id.
    #[must_use]
    #[inline]
    pub fn word_id(&self) -> u32 {
        self.occurrence.word_id()
    }
    /// Get a reference to the hit's document id.
    ///
    /// This might be any of the [`Self::occurrences`] if that returns any items.
    #[must_use]
    #[inline]
    pub fn start(&self) -> usize {
        self.occurrence.start()
    }
    /// Get a reference to the hit's occurrence.
    #[must_use]
    #[inline]
    pub fn occurrence(&self) -> &Occurence {
        &self.occurrence
    }
    /// Get the hit's rating.
    #[must_use]
    #[inline]
    pub fn rating(&self) -> f32 {
        self.occurrence.rating()
    }
    #[inline]
    fn rating_mut(&mut self) -> &mut f32 {
        self.occurrence.rating_mut()
    }
    /// [`Self::occurrence`] and all associated occurrences.
    #[inline]
    pub fn occurrences(&self) -> impl Iterator<Item = AssociatedOccurrence> + '_ {
        let first = if self.merged {
            None
        } else {
            Some(index::AssociatedOccurrence::new(
                self.start(),
                self.occurrence.word_id(),
            ))
        };
        first.into_iter().chain(self.occurrences.iter().copied())
    }

    /// Merges two [`Hit`]s, by adding the [`Hit::occurrences`] to our set.
    ///
    /// Must have the same [document id](Self::id()).
    fn merge(&mut self, other: &Self) {
        if self.occurrences.is_empty() {
            self.occurrences.insert((&*self).into());
        }
        for other_occ in other.occurrences() {
            self.occurrences.insert(other_occ);
        }
        self.occurrences.insert(other.into());
        self.merged = true;
    }
}
impl PartialEq for Hit {
    fn eq(&self, other: &Self) -> bool {
        self.id() == other.id() && self.start() == other.start()
    }
}
impl Eq for Hit {}
impl PartialOrd for Hit {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl Ord for Hit {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        use std::cmp::Ordering::Equal;
        match self.id().cmp(&other.id()) {
            Equal => self.start().cmp(&other.start()),
            cmp => cmp,
        }
    }
}

#[derive(Debug)]
pub enum IterError {
    StrayNot,
}

/// [`Query`] parsing.
pub mod parse {
    use std::fmt::{self, Debug, Display};
    use std::str::FromStr;

    use super::{BinaryPart, Part, Query};

    impl FromStr for Query {
        type Err = Error;
        fn from_str(s: &str) -> Result<Self, Self::Err> {
            s.parse().map(Query::new)
        }
    }
    impl FromStr for Part {
        type Err = Error;
        fn from_str(s: &str) -> Result<Self, Self::Err> {
            parse(s, Options::default())
        }
    }

    /// Parse `s` with `opts`.
    ///
    /// You can also use the [`FromStr`] trait implemented by [`Query`] and [`Part`]
    /// if you don't care about the [`Options`].
    #[allow(clippy::missing_panics_doc)]
    #[allow(clippy::missing_errors_doc)]
    pub fn parse(s: &str, opts: Options) -> Result<Part, Error> {
        let mut parser = Parser::new();
        let mut opts = opts;
        let opts = &mut opts;
        let mut rest = s;

        if s.is_empty() {
            return Err(Error::InputEmpty);
        }

        loop {
            let advance = parser.next(opts, rest)?;
            rest = if let Some(rest) = rest
                .char_indices()
                .nth(advance)
                .and_then(|(pos, _)| rest.get(pos..))
            {
                rest
            } else {
                return parser.finish();
            };

            if rest.is_empty() {
                return parser.finish();
            }
        }
    }

    #[derive(Debug, PartialEq, Eq)]
    pub enum StringMarkerError {
        /// The operation must be unary.
        OperationIsBinary,
    }

    /// The parser. This is public to allow you to change it's state when making a [`Rule`].
    #[derive(Debug)]
    pub struct Parser {
        sub: Option<Box<Parser>>,
        sub_layer: usize,
        pub left: Option<Part>,
        left_group_explicit: bool,
        pub string: String,
        string_marker: Option<Op>,
        old_op: Option<Op>,
        op: Option<Op>,
    }
    impl Parser {
        fn take_string(&mut self) -> Part {
            let string = std::mem::replace(&mut self.string, String::with_capacity(8));
            let part = Part::String(crate::index::Alphanumeral::new(&string).chars().collect());
            if let Some(marker) = self.string_marker.take() {
                match marker {
                    Op::Not => Part::not(part),
                    Op::And | Op::Or => {
                        unreachable!("In `set_string_marker`, we check for binary.")
                    }
                }
            } else {
                part
            }
        }
        /// # Errors
        ///
        /// Returns an error if `op` is [`Op::binary`].
        pub fn set_string_marker(&mut self, op: Op) -> Result<(), StringMarkerError> {
            if op.binary() {
                Err(StringMarkerError::OperationIsBinary)
            } else {
                self.string_marker = Some(op);
                Ok(())
            }
        }
        #[must_use]
        pub fn string_marker(&self) -> Option<Op> {
            self.string_marker
        }
        #[allow(clippy::missing_panics_doc)]
        pub fn set_op(&mut self, op: Op) {
            if op.binary() {
                self.op = Some(op);
            } else {
                // UNWRAP: See errors note and the if statement we're in.
                self.set_string_marker(op).unwrap();
            }
        }
        /// If the parser is completely empty, with no content.
        #[must_use]
        pub fn is_empty(&self) -> bool {
            self.old_op.is_none()
                && self.op.is_none()
                && self.string_marker.is_none()
                && self.string.is_empty()
                && self.sub.is_none()
                && self.left.is_none()
        }
        // start by appending to a Part::String
        // if any things (struct) are recogniced
        // add their corresponding part (method of struct, manip the tree)
        //
        // Make sure the order is right on those rules - order of importance: NOT, AND, OR
        /// # Panics
        ///
        /// Panics if `rest.is_empty()`.
        fn next(&mut self, opts: &mut Options, rest: &str) -> Result<usize, Error> {
            if let Some(sub) = &mut self.sub {
                if rest.starts_with('(') {
                    self.sub_layer += 1;
                }
                if rest.starts_with(')') {
                    self.sub_layer -= 1;
                    if self.sub_layer == 0 {
                        let parenthesis = sub.finish()?;
                        self.finish_part(self.old_op, parenthesis);
                        self.sub = None;
                        self.left_group_explicit = true;
                        return Ok(1);
                    }
                }
                return sub.next(opts, rest);
            } else if rest.starts_with('(') {
                self.sub = Some(Box::new(Self::new()));
                self.sub_layer += 1;
                return Ok(1);
            }

            let mut advance = None;
            for rule in &mut opts.rules {
                if let Some(result) = rule.next(self, rest) {
                    assert!(result > 0, "Cannot stay on the same byte.");

                    advance = Some(result);
                }
            }
            if let Some(advance) = advance {
                if !self.string.is_empty() {
                    match (self.op, self.old_op) {
                        (Some(_), None) => {
                            self.left = Some(self.take_string());
                        }
                        (_, Some(old_op)) => {
                            let right = self.take_string();
                            self.left = Some(self.finish_op(old_op, right));
                        }
                        _ => {}
                    }
                    self.left_group_explicit = false;
                }

                if let Some(op) = self.op {
                    self.old_op = Some(op);
                    self.op = None;
                }

                return Ok(advance);
            }
            let c = rest.chars().next().unwrap();
            if c.is_alphanumeric() {
                self.string.push(c);
            }
            Ok(1)
        }
        fn finish_part(&mut self, op: Option<Op>, mut right: Part) {
            if let Some(marker) = self.string_marker.take() {
                match marker {
                    Op::Not => right = Part::not(right),
                    Op::And | Op::Or => {
                        unreachable!("In `set_string_marker`, we check for binary.")
                    }
                }
            }
            if let Some(op) = op {
                self.left = Some(self.finish_op(op, right));
            } else {
                self.left = Some(right);
            }
        }
        fn finish_op(&mut self, op: Op, mut right: Part) -> Part {
            if let Op::And | Op::Or = op {
                if self.left.is_none() {
                    return right;
                }
            }
            match op {
                Op::And => {
                    // UNWRAP: See if statement in top of fn
                    let left = self.left.take().unwrap();

                    if let Part::Or(mut pair) = left {
                        if self.left_group_explicit {
                            Part::And(BinaryPart::new(Part::Or(pair), right).into_box())
                        } else {
                            std::mem::swap(&mut right, &mut pair.left);
                            pair.swap();
                            let and = Part::And(pair);
                            // We swapped the left part of the pair to `right`.
                            let or = right;
                            Part::or(or, and)
                        }
                    } else {
                        Part::And(BinaryPart::new(left, right).into_box())
                    }
                }
                Op::Or => {
                    // UNWRAP: See if statement in top of fn
                    let left = self.left.take().unwrap();
                    Part::Or(BinaryPart::new(left, right).into_box())
                }
                Op::Not => Part::Not(Box::new(right)),
            }
        }
        fn finish(&mut self) -> Result<Part, Error> {
            if !self.string.is_empty() {
                let right = self.take_string();
                self.finish_part(self.old_op, right);
            }
            self.left.take().ok_or_else(|| {
                if self.is_empty() {
                    Error::InputEmpty
                } else {
                    Error::NotEnoughArguments
                }
            })
        }
        fn new() -> Self {
            Self {
                sub: None,
                sub_layer: 0,
                left: None,
                left_group_explicit: false,
                string: String::with_capacity(8),
                string_marker: None,
                old_op: None,
                op: None,
            }
        }
    }

    #[derive(Debug, Clone, Copy)]
    pub enum Op {
        And,
        Or,
        Not,
    }
    impl Op {
        #[must_use]
        pub fn binary(&self) -> bool {
            matches!(self, Self::And | Self::Or)
        }
    }

    #[derive(Debug, PartialEq, Eq, Clone)]
    pub enum Error {
        InputEmpty,
        /// Operation took more arguments than what was supplied.
        NotEnoughArguments,
        UnexpectedParentheses,
    }
    impl Display for Error {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            match self {
                Self::InputEmpty => f.write_str("input empty"),
                Self::NotEnoughArguments => f.write_str(
                    "logic operation got too few arguments (missing word after AND or OR?)",
                ),
                Self::UnexpectedParentheses => f.write_str("parentheses in an unexpected place"),
            }
        }
    }

    /// Same as [`char::is_ascii_whitespace`], but including `\u{a0}`, non-breaking space.
    #[must_use]
    pub fn is_whitespace(c: char) -> bool {
        c.is_ascii_whitespace() || c == '\u{a0}'
    }

    /// Options to [`parse`]. Here, you can add your own formatting rules, on top of the default
    /// rules.
    #[derive(Debug)]
    #[must_use]
    pub struct Options {
        rules: Vec<Box<dyn Rule>>,
    }
    impl Options {
        /// Crates a new, empty, set of options.
        /// The order of [`Self::insert`] matters a lot.
        ///
        /// [`Self::populate_and_space`] should definitely be last.
        ///
        /// See [`crate::literal_rule!`] for an example.
        pub fn new() -> Self {
            Self { rules: Vec::new() }
        }
        pub fn insert<R: 'static + Rule>(mut self, rule: R) -> Self {
            self.rules.push(Box::new(rule));
            self
        }
        pub fn populate_literals(self) -> Self {
            self.insert(NotLiteral::default())
                .insert(AndLiteral::default())
                .insert(OrLiteral::default())
        }
        pub fn populate_not(self) -> Self {
            self.insert(DashNot::default()).insert(BangNot::default())
        }
        pub fn populate_and_space(self) -> Self {
            self.insert(AndSpace::default())
        }
    }
    impl Default for Options {
        fn default() -> Self {
            Self::new()
                .populate_literals()
                .populate_not()
                .populate_and_space()
        }
    }
    pub trait Rule: Debug {
        /// # Returns
        ///
        /// If the match is successful, make changes to the `parser` (e.g. [`Parser::set_op`])
        /// and return [`Some`] with the number of steps to step forward (length of operator).
        #[must_use]
        fn next(&mut self, parser: &mut Parser, rest: &str) -> Option<usize>;
    }

    #[derive(Debug, Default)]
    pub struct AndSpace {
        last_was_other_op: bool,
    }
    impl Rule for AndSpace {
        fn next(&mut self, parser: &mut Parser, rest: &str) -> Option<usize> {
            if parser.string_marker().is_some() && parser.string.is_empty() {
                return None;
            }
            if parser.is_empty() {
                return None;
            }
            if !self.last_was_other_op {
                self.last_was_other_op = parser.op.is_some();
                if self.last_was_other_op {
                    return None;
                }
            }
            let c = rest.chars().next().unwrap();
            if self.last_was_other_op {
                if is_whitespace(c) || c == '-' {
                    None
                } else {
                    self.last_was_other_op = false;
                    None
                }
            } else if is_whitespace(c) || c == '-' {
                parser.op = Some(Op::And);
                Some(1)
            } else {
                None
            }
        }
    }

    /// Used in [parsing](self).
    ///
    /// # Examples
    ///
    /// See [`crate::literal_rule!`] and [`crate::not_prefix!`].
    ///
    /// ```
    /// use elipdotter::*;
    /// use elipdotter::query::Part;
    /// use elipdotter::query::parse::LiteralRule;
    /// generate_rule!(EllerLiteral, LiteralRule, LiteralRule::new("eller", query::parse::Op::Or));
    /// let opts = elipdotter::query::ParseOptions::new().populate_literals().insert(EllerLiteral::default()).populate_not().populate_and_space();
    /// let part = elipdotter::query::parse("elipdotter eller search", opts).unwrap();
    /// assert_eq!(part, Part::or("elipdotter", "search"));
    /// ```
    #[macro_export]
    macro_rules! generate_rule {
        ($name: ident, $struct: path, $new: expr) => {
            #[derive(Debug)]
            #[must_use]
            pub struct $name($struct);
            impl $name {
                pub fn new() -> Self {
                    Self($new)
                }
            }
            impl Default for $name {
                fn default() -> Self {
                    Self::new()
                }
            }
            impl $crate::query::parse::Rule for $name {
                fn next(
                    &mut self,
                    parser: &mut $crate::query::parse::Parser,
                    rest: &str,
                ) -> Option<usize> {
                    self.0.next(parser, rest)
                }
            }
        };
    }

    #[derive(Debug)]
    #[must_use]
    pub struct LiteralRule {
        literal: &'static str,
        op: Op,
        last_was_space: bool,
    }
    impl LiteralRule {
        /// Matches the `literal` with [`Op`].
        ///
        /// Will exit if nothing was detected before and this is a binary operation.
        pub fn new(literal: &'static str, op: Op) -> Self {
            Self {
                literal,
                op,
                last_was_space: true,
            }
        }
    }
    impl Rule for LiteralRule {
        fn next(&mut self, parser: &mut Parser, rest: &str) -> Option<usize> {
            if self.op.binary() && parser.string.is_empty() && parser.left.is_none() {
                self.last_was_space = rest.chars().next().map_or(false, is_whitespace);
                return None;
            }
            let rule = if self.last_was_space
                && rest
                    .get(0..self.literal.len())
                    .map_or(false, |rest| rest.eq_ignore_ascii_case(self.literal))
                && rest
                    .chars()
                    .nth(self.literal.len())
                    .map_or(false, is_whitespace)
            {
                parser.set_op(self.op);
                Some(self.literal.len())
            } else {
                None
            };

            self.last_was_space = rest.chars().next().map_or(false, is_whitespace);

            rule
        }
    }

    /// Used in [parsing](self).
    ///
    /// # Examples
    ///
    /// ```
    /// use elipdotter::*;
    /// use elipdotter::query::Part;
    /// literal_rule!(EllerLiteral, "eller", query::parse::Op::Or);
    /// let opts = elipdotter::query::ParseOptions::new().populate_literals().insert(EllerLiteral::default()).populate_not().populate_and_space();
    /// let part = elipdotter::query::parse("elipdotter eller search", opts).unwrap();
    /// assert_eq!(part, Part::or("elipdotter", "search"));
    /// ```
    #[macro_export]
    macro_rules! literal_rule {
        ($name: ident, $literal: expr, $op: expr) => {
            $crate::generate_rule!(
                $name,
                $crate::query::parse::LiteralRule,
                $crate::query::parse::LiteralRule::new($literal, $op)
            );
        };
    }

    literal_rule!(AndLiteral, "and", Op::And);
    literal_rule!(OrLiteral, "or", Op::Or);
    literal_rule!(NotLiteral, "not", Op::Not);

    #[derive(Debug)]
    #[must_use]
    pub struct NotPrefix {
        prefix: &'static str,
        last_was_space: bool,
    }
    impl NotPrefix {
        pub fn new(prefix: &'static str) -> Self {
            Self {
                prefix,
                last_was_space: true,
            }
        }
    }
    impl Rule for NotPrefix {
        fn next(&mut self, parser: &mut Parser, rest: &str) -> Option<usize> {
            let rule = if self.last_was_space && rest.starts_with(self.prefix) {
                parser.set_op(Op::Not);
                Some(self.prefix.len())
            } else {
                None
            };

            self.last_was_space = rest.chars().next().map_or(false, is_whitespace);

            rule
        }
    }

    /// Used in [parsing](self).
    ///
    /// # Examples
    ///
    /// ```
    /// use elipdotter::*;
    /// use elipdotter::query::Part;
    /// not_prefix!(HyphenNot, "-");
    /// let opts = elipdotter::query::ParseOptions::default().insert(HyphenNot::default());
    /// let part = elipdotter::query::parse("elipdotter -search", opts).unwrap();
    /// assert_eq!(part, Part::and("elipdotter", Part::not("search")));
    /// ```
    #[macro_export]
    macro_rules! not_prefix {
        ($name: ident, $prefix: expr) => {
            $crate::generate_rule!(
                $name,
                $crate::query::parse::NotPrefix,
                $crate::query::parse::NotPrefix::new($prefix)
            );
        };
    }
    not_prefix!(DashNot, "-");
    not_prefix!(BangNot, "!");
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Parses `s` with [`ParseOptions::default`].
    fn s(s: &str) -> Part {
        match parse(s, ParseOptions::default()) {
            Ok(p) => p,
            Err(err) => {
                panic!("Failed to parse '{}', {:?}", s, err);
            }
        }
    }

    #[test]
    fn binary_swap_eq() {
        let part = s("icelk kvarn");
        let mut swapped = part.clone();
        if let Part::And(pair) = &mut swapped {
            pair.swap();
        } else {
            panic!("Isn't Add.");
        }
        assert_eq!(part, swapped);
    }

    #[test]
    fn parse_and() {
        let input = "icelk kvarn";
        let part = s(input);
        assert_eq!(part, Part::and("icelk", "kvarn"));
    }
    #[test]
    fn parse_and_chain() {
        let input = "icelk kvarn web server";
        let part = s(input);
        assert_eq!(
            part,
            Part::and(Part::and(Part::and("icelk", "kvarn"), "web"), "server")
        );
    }
    #[test]
    fn parse_plain_not() {
        let part = s("not icelk");
        assert_eq!(part, Part::not("icelk"));
    }
    #[test]
    fn parse_plain_or() {
        let p = s("or");
        assert_eq!(p, Part::s("or"));
        let p = s("for me");
        assert_eq!(p, Part::and("for", "me"));
    }
    #[test]
    fn parse_empty() {
        assert_eq!(
            parse("", ParseOptions::default()).unwrap_err(),
            parse::Error::InputEmpty
        );
    }
    #[test]
    fn parse_without_ops() {
        assert_eq!(s("icelk"), Part::s("icelk"),);
    }
    #[test]
    fn parse_and_before_or() {
        let i1 = "icelk and kvarn or agde";
        let i2 = "agde or icelk and kvarn";
        let p1 = s(i1);
        let p2 = s(i2);

        let correct = Part::or(Part::and("icelk", "kvarn"), "agde");
        assert_eq!(p1, correct);
        assert!(p1.eq_order(&correct));
        assert_eq!(p2, correct);
        assert!(!p2.eq_order(&correct));
        assert_eq!(p1, p2);

        let implicit = "icelk kvarn or agde";
        let p_impl = s(implicit);

        assert_eq!(p_impl, p1);
    }
    #[test]
    fn parse_parentheses_or() {
        let p1 = s("(icelk or kvarn) and code");
        let p2 = s("code (kvarn or icelk) ");

        let correct = Part::and(Part::or("icelk", "kvarn"), "code");

        assert_eq!(p1, correct);
        assert!(p1.eq_order(&correct));
        assert_eq!(p2, correct);
        assert!(!p2.eq_order(&correct));
        assert_eq!(p1, p2);
    }
    #[test]
    fn parse_parentheses_and() {
        let p = s(" (icelk or iselk)  (kvarn or agde)))");
        assert_eq!(
            p,
            Part::and(Part::or("icelk", "iselk"), Part::or("kvarn", "agde"))
        );
    }
    #[test]
    fn parse_parentheses_and_not() {
        let p = s("icelk -(agde or kvarn)");
        assert_eq!(p, Part::and("icelk", Part::not(Part::or("kvarn", "agde"))));

        let p = s("icelk - (agde or kvarn)");
        assert_eq!(p, Part::and("icelk", Part::not(Part::or("kvarn", "agde"))));
    }
    #[test]
    fn parse_not() {
        let p = s("not");
        assert_eq!(p, Part::s("not"));
        assert_eq!(
            parse("not ", ParseOptions::default()).unwrap_err(),
            parse::Error::NotEnoughArguments
        );
    }
    #[test]
    fn parse_space() {
        assert_eq!(
            parse(" ", ParseOptions::default()).unwrap_err(),
            parse::Error::InputEmpty
        );
    }
    #[test]
    fn parse_parentheses_space() {
        assert_eq!(
            parse(" (  ) ", ParseOptions::default()).unwrap_err(),
            parse::Error::InputEmpty,
        );
    }
    #[test]
    fn parse_binary_one_arg() {
        let p = s("or icelk");
        assert_eq!(p, Part::and("or", "icelk"));
    }
    #[test]
    fn parse_parentheses_binary_one_arg() {
        let p = s("(or (icelk))");
        assert_eq!(p, Part::and("or", "icelk"));
    }
    #[test]
    fn parse_operation_order() {
        let p = s("icelk and not kvarn or agde");
        assert_eq!(p, Part::or(Part::and("icelk", Part::not("kvarn")), "agde"));

        let p = s("icelk or not kvarn or agde");
        assert_eq!(p, Part::or(Part::or("icelk", Part::not("kvarn")), "agde"));

        let p = s("agde not sync or icelk and not kvarn or agde");
        assert_eq!(
            p,
            Part::or(
                Part::or(
                    Part::and("agde", Part::not("sync")),
                    Part::and("icelk", Part::not("kvarn"))
                ),
                "agde"
            )
        );
    }
    #[test]
    fn parse_prefix_not() {
        assert_eq!(s("icelk !kvarn"), s("icelk -kvarn"));
        assert_eq!(s("icelk !kvarn"), Part::and("icelk", Part::not("kvarn")));
        assert_eq!(
            s("elipdotter -search"),
            Part::and("elipdotter", Part::not("search"))
        );
    }
    #[test]
    fn parse_non_alphanumeral() {
        assert_eq!(s("icelk.dev"), Part::s("icelkdev"));
        assert_eq!(
            s("next-generation kvarn"),
            Part::and(Part::and("next", "generation"), "kvarn")
        );
    }

    fn p_disp_match(string: &str) {
        let p = s(string);
        assert_eq!(p, s(&p.to_string()));
    }
    #[test]
    fn parse_display() {
        p_disp_match("agde not sync or icelk and not kvarn or agde");
        p_disp_match(" ( kvarn ) icelk ");
        p_disp_match(" (icelk or iselk)  (kvarn or agde)))");
        p_disp_match("(or (icelk))");
    }
}