harper_core/
document.rs

1use std::cmp::Ordering;
2use std::collections::VecDeque;
3use std::fmt::Display;
4
5use harper_brill::{Chunker, Tagger, brill_tagger, burn_chunker};
6use paste::paste;
7
8use crate::expr::{Expr, ExprExt, FirstMatchOf, Repeating, SequenceExpr};
9use crate::parsers::{Markdown, MarkdownOptions, Parser, PlainEnglish};
10use crate::patterns::WordSet;
11use crate::punctuation::Punctuation;
12use crate::spell::{Dictionary, FstDictionary};
13use crate::vec_ext::VecExt;
14use crate::{FatStringToken, FatToken, Lrc, Token, TokenKind, TokenStringExt};
15use crate::{OrdinalSuffix, Span};
16
17/// A document containing some amount of lexed and parsed English text.
18#[derive(Debug, Clone)]
19pub struct Document {
20    source: Lrc<Vec<char>>,
21    tokens: Vec<Token>,
22}
23
24impl Default for Document {
25    fn default() -> Self {
26        Self::new("", &PlainEnglish, &FstDictionary::curated())
27    }
28}
29
30impl Document {
31    /// Locate all the tokens that intersect a provided span.
32    ///
33    /// Desperately needs optimization.
34    pub fn token_indices_intersecting(&self, span: Span<char>) -> Vec<usize> {
35        self.tokens()
36            .enumerate()
37            .filter_map(|(idx, tok)| tok.span.overlaps_with(span).then_some(idx))
38            .collect()
39    }
40
41    /// Locate all the tokens that intersect a provided span and convert them to [`FatToken`]s.
42    ///
43    /// Desperately needs optimization.
44    pub fn fat_tokens_intersecting(&self, span: Span<char>) -> Vec<FatToken> {
45        let indices = self.token_indices_intersecting(span);
46
47        indices
48            .into_iter()
49            .map(|i| self.tokens[i].to_fat(&self.source))
50            .collect()
51    }
52
53    /// Lexes and parses text to produce a document using a provided language
54    /// parser and dictionary.
55    pub fn new(text: &str, parser: &impl Parser, dictionary: &impl Dictionary) -> Self {
56        let source: Vec<_> = text.chars().collect();
57
58        Self::new_from_vec(Lrc::new(source), parser, dictionary)
59    }
60
61    /// Lexes and parses text to produce a document using a provided language
62    /// parser and the included curated dictionary.
63    pub fn new_curated(text: &str, parser: &impl Parser) -> Self {
64        let source: Vec<_> = text.chars().collect();
65
66        Self::new_from_vec(Lrc::new(source), parser, &FstDictionary::curated())
67    }
68
69    /// Lexes and parses text to produce a document using a provided language
70    /// parser and dictionary.
71    pub fn new_from_vec(
72        source: Lrc<Vec<char>>,
73        parser: &impl Parser,
74        dictionary: &impl Dictionary,
75    ) -> Self {
76        let tokens = parser.parse(&source);
77
78        let mut document = Self { source, tokens };
79        document.parse(dictionary);
80
81        document
82    }
83
84    /// Parse text to produce a document using the built-in [`PlainEnglish`]
85    /// parser and curated dictionary.
86    pub fn new_plain_english_curated(text: &str) -> Self {
87        Self::new(text, &PlainEnglish, &FstDictionary::curated())
88    }
89
90    /// Parse text to produce a document using the built-in [`PlainEnglish`]
91    /// parser and a provided dictionary.
92    pub fn new_plain_english(text: &str, dictionary: &impl Dictionary) -> Self {
93        Self::new(text, &PlainEnglish, dictionary)
94    }
95
96    /// Parse text to produce a document using the built-in [`Markdown`] parser
97    /// and curated dictionary.
98    pub fn new_markdown_curated(text: &str, markdown_options: MarkdownOptions) -> Self {
99        Self::new(
100            text,
101            &Markdown::new(markdown_options),
102            &FstDictionary::curated(),
103        )
104    }
105
106    /// Parse text to produce a document using the built-in [`Markdown`] parser
107    /// and curated dictionary with the default Markdown configuration.
108    pub fn new_markdown_default_curated(text: &str) -> Self {
109        Self::new_markdown_curated(text, MarkdownOptions::default())
110    }
111
112    /// Parse text to produce a document using the built-in [`PlainEnglish`]
113    /// parser and the curated dictionary.
114    pub fn new_markdown(
115        text: &str,
116        markdown_options: MarkdownOptions,
117        dictionary: &impl Dictionary,
118    ) -> Self {
119        Self::new(text, &Markdown::new(markdown_options), dictionary)
120    }
121
122    /// Parse text to produce a document using the built-in [`PlainEnglish`]
123    /// parser and the curated dictionary with the default Markdown configuration.
124    pub fn new_markdown_default(text: &str, dictionary: &impl Dictionary) -> Self {
125        Self::new_markdown(text, MarkdownOptions::default(), dictionary)
126    }
127
128    /// Re-parse important language constructs.
129    ///
130    /// Should be run after every change to the underlying [`Self::source`].
131    fn parse(&mut self, dictionary: &impl Dictionary) {
132        self.condense_spaces();
133        self.condense_newlines();
134        self.newlines_to_breaks();
135        self.condense_contractions();
136        self.condense_dotted_initialisms();
137        self.condense_number_suffixes();
138        self.condense_ellipsis();
139        self.condense_latin();
140        self.condense_filename_extensions();
141        self.match_quotes();
142
143        let chunker = burn_chunker();
144        let tagger = brill_tagger();
145
146        for sent in self.tokens.iter_sentences_mut() {
147            let token_strings: Vec<_> = sent
148                .iter()
149                .filter(|t| !t.kind.is_whitespace())
150                .map(|t| t.span.get_content_string(&self.source))
151                .collect();
152
153            let token_tags = tagger.tag_sentence(&token_strings);
154            let np_flags = chunker.chunk_sentence(&token_strings, &token_tags);
155
156            let mut i = 0;
157
158            // Annotate word metadata
159            for token in sent.iter_mut() {
160                if let TokenKind::Word(meta) = &mut token.kind {
161                    let word_source = token.span.get_content(&self.source);
162                    let mut found_meta = dictionary.get_word_metadata(word_source).cloned();
163
164                    if let Some(inner) = &mut found_meta {
165                        inner.pos_tag = token_tags[i].or_else(|| inner.infer_pos_tag());
166                        inner.np_member = Some(np_flags[i]);
167                    }
168
169                    *meta = found_meta;
170                    i += 1;
171                } else if !token.kind.is_whitespace() {
172                    i += 1;
173                }
174            }
175        }
176    }
177
178    /// Convert all sets of newlines greater than 2 to paragraph breaks.
179    fn newlines_to_breaks(&mut self) {
180        for token in &mut self.tokens {
181            if let TokenKind::Newline(n) = token.kind {
182                if n >= 2 {
183                    token.kind = TokenKind::ParagraphBreak;
184                }
185            }
186        }
187    }
188
189    /// Given a list of indices, this function removes the subsequent
190    /// `stretch_len - 1` elements after each index.
191    ///
192    /// Will extend token spans to include removed elements.
193    /// Assumes condensed tokens are contiguous in source text.
194    fn condense_indices(&mut self, indices: &[usize], stretch_len: usize) {
195        // Update spans
196        for idx in indices {
197            let end_tok = self.tokens[idx + stretch_len - 1].clone();
198            let start_tok = &mut self.tokens[*idx];
199
200            start_tok.span.end = end_tok.span.end;
201        }
202
203        // Trim
204        let old = self.tokens.clone();
205        self.tokens.clear();
206
207        // Keep first chunk.
208        self.tokens
209            .extend_from_slice(&old[0..indices.first().copied().unwrap_or(indices.len())]);
210
211        let mut iter = indices.iter().peekable();
212
213        while let (Some(a_idx), b) = (iter.next(), iter.peek()) {
214            self.tokens.push(old[*a_idx].clone());
215
216            if let Some(b_idx) = b {
217                self.tokens
218                    .extend_from_slice(&old[a_idx + stretch_len..**b_idx]);
219            }
220        }
221
222        // Keep last chunk.
223        self.tokens.extend_from_slice(
224            &old[indices
225                .last()
226                .map(|v| v + stretch_len)
227                .unwrap_or(indices.len())..],
228        );
229    }
230
231    pub fn get_token_at_char_index(&self, char_index: usize) -> Option<&Token> {
232        let index = self
233            .tokens
234            .binary_search_by(|t| {
235                if t.span.overlaps_with(Span::new_with_len(char_index, 1)) {
236                    Ordering::Equal
237                } else {
238                    t.span.start.cmp(&char_index)
239                }
240            })
241            .ok()?;
242
243        Some(&self.tokens[index])
244    }
245
246    /// Defensively attempt to grab a specific token.
247    pub fn get_token(&self, index: usize) -> Option<&Token> {
248        self.tokens.get(index)
249    }
250
251    /// Get a token at a signed offset from a base index, or None if out of bounds.
252    pub fn get_token_offset(&self, base: usize, offset: isize) -> Option<&Token> {
253        match base.checked_add_signed(offset) {
254            None => None,
255            Some(idx) => self.get_token(idx),
256        }
257    }
258
259    /// Get an iterator over all the tokens contained in the document.
260    pub fn tokens(&self) -> impl Iterator<Item = &Token> + '_ {
261        self.tokens.iter()
262    }
263
264    pub fn iter_nominal_phrases(&self) -> impl Iterator<Item = &[Token]> {
265        fn is_np_member(t: &Token) -> bool {
266            t.kind
267                .as_word()
268                .and_then(|x| x.as_ref())
269                .and_then(|w| w.np_member)
270                .unwrap_or(false)
271        }
272
273        fn trim(slice: &[Token]) -> &[Token] {
274            let mut start = 0;
275            let mut end = slice.len();
276            while start < end && slice[start].kind.is_whitespace() {
277                start += 1;
278            }
279            while end > start && slice[end - 1].kind.is_whitespace() {
280                end -= 1;
281            }
282            &slice[start..end]
283        }
284
285        self.tokens
286            .as_slice()
287            .split(|t| !(is_np_member(t) || t.kind.is_whitespace()))
288            .filter_map(|s| {
289                let s = trim(s);
290                if s.iter().any(is_np_member) {
291                    Some(s)
292                } else {
293                    None
294                }
295            })
296    }
297
298    /// Get an iterator over all the tokens contained in the document.
299    pub fn fat_tokens(&self) -> impl Iterator<Item = FatToken> + '_ {
300        self.tokens().map(|token| token.to_fat(&self.source))
301    }
302
303    /// Get the next or previous word token relative to a base index, if separated by whitespace.
304    /// Returns None if the next/previous token is not a word or does not exist.
305    pub fn get_next_word_from_offset(&self, base: usize, offset: isize) -> Option<&Token> {
306        // Look for whitespace at the expected offset
307        if !self.get_token_offset(base, offset)?.kind.is_whitespace() {
308            return None;
309        }
310        // Now look beyond the whitespace for a word token
311        let word_token = self.get_token_offset(base, offset + offset.signum());
312        let word_token = word_token?;
313        word_token.kind.is_word().then_some(word_token)
314    }
315
316    /// Get an iterator over all the tokens contained in the document.
317    pub fn fat_string_tokens(&self) -> impl Iterator<Item = FatStringToken> + '_ {
318        self.fat_tokens().map(|t| t.into())
319    }
320
321    pub fn get_span_content(&self, span: &Span<char>) -> &[char] {
322        span.get_content(&self.source)
323    }
324
325    pub fn get_span_content_str(&self, span: &Span<char>) -> String {
326        String::from_iter(self.get_span_content(span))
327    }
328
329    pub fn get_full_string(&self) -> String {
330        self.get_span_content_str(&Span::new(0, self.source.len()))
331    }
332
333    pub fn get_full_content(&self) -> &[char] {
334        &self.source
335    }
336
337    pub fn get_source(&self) -> &[char] {
338        &self.source
339    }
340
341    pub fn get_tokens(&self) -> &[Token] {
342        &self.tokens
343    }
344
345    /// Searches for quotation marks and fills the
346    /// [`Punctuation::Quote::twin_loc`] field. This is on a best-effort
347    /// basis.
348    ///
349    /// Current algorithm is basic and could use some work.
350    fn match_quotes(&mut self) {
351        let quote_indices: Vec<usize> = self.tokens.iter_quote_indices().collect();
352
353        for i in 0..quote_indices.len() / 2 {
354            let a_i = quote_indices[i * 2];
355            let b_i = quote_indices[i * 2 + 1];
356
357            {
358                let a = self.tokens[a_i].kind.as_mut_quote().unwrap();
359                a.twin_loc = Some(b_i);
360            }
361
362            {
363                let b = self.tokens[b_i].kind.as_mut_quote().unwrap();
364                b.twin_loc = Some(a_i);
365            }
366        }
367    }
368
369    /// Searches for number suffixes and condenses them down into single tokens
370    fn condense_number_suffixes(&mut self) {
371        if self.tokens.len() < 2 {
372            return;
373        }
374
375        let mut replace_starts = Vec::new();
376
377        for idx in 0..self.tokens.len() - 1 {
378            let b = &self.tokens[idx + 1];
379            let a = &self.tokens[idx];
380
381            // TODO: Allow spaces between `a` and `b`
382
383            if let (TokenKind::Number(..), TokenKind::Word(..)) = (&a.kind, &b.kind) {
384                if let Some(found_suffix) =
385                    OrdinalSuffix::from_chars(self.get_span_content(&b.span))
386                {
387                    self.tokens[idx].kind.as_mut_number().unwrap().suffix = Some(found_suffix);
388                    replace_starts.push(idx);
389                }
390            }
391        }
392
393        self.condense_indices(&replace_starts, 2);
394    }
395
396    /// Searches for multiple sequential space tokens and condenses them down
397    /// into one.
398    fn condense_spaces(&mut self) {
399        let mut cursor = 0;
400        let copy = self.tokens.clone();
401
402        let mut remove_these = VecDeque::new();
403
404        while cursor < self.tokens.len() {
405            // Locate a stretch of one or more newline tokens.
406            let start_tok = &mut self.tokens[cursor];
407
408            if let TokenKind::Space(start_count) = &mut start_tok.kind {
409                loop {
410                    cursor += 1;
411
412                    if cursor >= copy.len() {
413                        break;
414                    }
415
416                    let child_tok = &copy[cursor];
417
418                    // Only condense adjacent spans
419                    if start_tok.span.end != child_tok.span.start {
420                        break;
421                    }
422
423                    if let TokenKind::Space(n) = child_tok.kind {
424                        *start_count += n;
425                        start_tok.span.end = child_tok.span.end;
426                        remove_these.push_back(cursor);
427                        cursor += 1;
428                    } else {
429                        break;
430                    };
431                }
432            }
433
434            cursor += 1;
435        }
436
437        self.tokens.remove_indices(remove_these);
438    }
439
440    thread_local! {
441        static LATIN_EXPR: Lrc<FirstMatchOf> = Document::uncached_latin_expr();
442    }
443
444    fn uncached_latin_expr() -> Lrc<FirstMatchOf> {
445        Lrc::new(FirstMatchOf::new(vec![
446            Box::new(
447                SequenceExpr::default()
448                    .then(WordSet::new(&["etc", "vs"]))
449                    .then_period(),
450            ),
451            Box::new(
452                SequenceExpr::aco("et")
453                    .then_whitespace()
454                    .t_aco("al")
455                    .then_period(),
456            ),
457        ]))
458    }
459
460    /// Assumes that the first matched token is the canonical one to be condensed into.
461    /// Takes a callback that can be used to retroactively edit the canonical token afterwards.
462    fn condense_expr<F>(&mut self, expr: &impl Expr, edit: F)
463    where
464        F: Fn(&mut Token),
465    {
466        let matches = expr.iter_matches_in_doc(self).collect::<Vec<_>>();
467
468        let mut remove_indices = VecDeque::with_capacity(matches.len());
469
470        for m in matches {
471            remove_indices.extend(m.start + 1..m.end);
472            self.tokens[m.start].span = self.tokens[m.into_iter()].span().unwrap();
473            edit(&mut self.tokens[m.start]);
474        }
475
476        self.tokens.remove_indices(remove_indices);
477    }
478
479    fn condense_latin(&mut self) {
480        self.condense_expr(&Self::LATIN_EXPR.with(|v| v.clone()), |_| {})
481    }
482
483    /// Searches for multiple sequential newline tokens and condenses them down
484    /// into one.
485    fn condense_newlines(&mut self) {
486        let mut cursor = 0;
487        let copy = self.tokens.clone();
488
489        let mut remove_these = VecDeque::new();
490
491        while cursor < self.tokens.len() {
492            // Locate a stretch of one or more newline tokens.
493            let start_tok = &mut self.tokens[cursor];
494
495            if let TokenKind::Newline(start_count) = &mut start_tok.kind {
496                loop {
497                    cursor += 1;
498
499                    if cursor >= copy.len() {
500                        break;
501                    }
502
503                    let child_tok = &copy[cursor];
504                    if let TokenKind::Newline(n) = child_tok.kind {
505                        *start_count += n;
506                        start_tok.span.end = child_tok.span.end;
507                        remove_these.push_back(cursor);
508                        cursor += 1;
509                    } else {
510                        break;
511                    };
512                }
513            }
514
515            cursor += 1;
516        }
517
518        self.tokens.remove_indices(remove_these);
519    }
520
521    /// Condenses words like "i.e.", "e.g." and "N.S.A." down to single words
522    /// using a state machine.
523    fn condense_dotted_initialisms(&mut self) {
524        if self.tokens.len() < 2 {
525            return;
526        }
527
528        let mut to_remove = VecDeque::new();
529
530        let mut cursor = 1;
531
532        let mut initialism_start = None;
533
534        loop {
535            let a = &self.tokens[cursor - 1];
536            let b = &self.tokens[cursor];
537
538            let is_initialism_chunk = a.kind.is_word() && a.span.len() == 1 && b.kind.is_period();
539
540            if is_initialism_chunk {
541                if initialism_start.is_none() {
542                    initialism_start = Some(cursor - 1);
543                } else {
544                    to_remove.push_back(cursor - 1);
545                }
546
547                to_remove.push_back(cursor);
548                cursor += 1;
549            } else {
550                if let Some(start) = initialism_start {
551                    let end = self.tokens[cursor - 2].span.end;
552                    let start_tok: &mut Token = &mut self.tokens[start];
553                    start_tok.span.end = end;
554                }
555
556                initialism_start = None;
557            }
558
559            cursor += 1;
560
561            if cursor >= self.tokens.len() - 1 {
562                break;
563            }
564        }
565
566        self.tokens.remove_indices(to_remove);
567    }
568
569    /// Condenses likely filename extensions down to single tokens.
570    fn condense_filename_extensions(&mut self) {
571        if self.tokens.len() < 2 {
572            return;
573        }
574
575        let mut to_remove = VecDeque::new();
576
577        let mut cursor = 1;
578
579        let mut ext_start = None;
580
581        loop {
582            // left context, dot, extension, right context
583            let l = self.get_token_offset(cursor, -2);
584            let d = &self.tokens[cursor - 1];
585            let x = &self.tokens[cursor];
586            let r = self.get_token_offset(cursor, 1);
587
588            let is_ext_chunk = d.kind.is_period()
589                && x.kind.is_word()
590                && x.span.len() <= 3
591                && ((l.is_none_or(|t| t.kind.is_whitespace())
592                    && r.is_none_or(|t| t.kind.is_whitespace()))
593                    || (l.is_some_and(|t| t.kind.is_open_round())
594                        && r.is_some_and(|t| t.kind.is_close_round())))
595                && {
596                    let ext_chars = x.span.get_content(&self.source);
597                    ext_chars.iter().all(|c| c.is_ascii_lowercase())
598                        || ext_chars.iter().all(|c| c.is_ascii_uppercase())
599                };
600
601            if is_ext_chunk {
602                if ext_start.is_none() {
603                    ext_start = Some(cursor - 1);
604                    self.tokens[cursor - 1].kind = TokenKind::Unlintable;
605                } else {
606                    to_remove.push_back(cursor - 1);
607                }
608
609                to_remove.push_back(cursor);
610                cursor += 1;
611            } else {
612                if let Some(start) = ext_start {
613                    let end = self.tokens[cursor - 2].span.end;
614                    let start_tok: &mut Token = &mut self.tokens[start];
615                    start_tok.span.end = end;
616                }
617
618                ext_start = None;
619            }
620
621            cursor += 1;
622
623            if cursor >= self.tokens.len() {
624                break;
625            }
626        }
627
628        self.tokens.remove_indices(to_remove);
629    }
630
631    fn uncached_ellipsis_pattern() -> Lrc<Repeating> {
632        let period = SequenceExpr::default().then_period();
633        Lrc::new(Repeating::new(Box::new(period), 2))
634    }
635
636    thread_local! {
637        static ELLIPSIS_EXPR: Lrc<Repeating> = Document::uncached_ellipsis_pattern();
638    }
639
640    fn condense_ellipsis(&mut self) {
641        let expr = Self::ELLIPSIS_EXPR.with(|v| v.clone());
642        self.condense_expr(&expr, |tok| {
643            tok.kind = TokenKind::Punctuation(Punctuation::Ellipsis)
644        });
645    }
646
647    fn uncached_contraction_expr() -> Lrc<SequenceExpr> {
648        Lrc::new(
649            SequenceExpr::default()
650                .then_any_word()
651                .then_apostrophe()
652                .then_any_word(),
653        )
654    }
655
656    thread_local! {
657        static CONTRACTION_EXPR: Lrc<SequenceExpr> = Document::uncached_contraction_expr();
658    }
659
660    /// Searches for contractions and condenses them down into single
661    /// tokens.
662    fn condense_contractions(&mut self) {
663        let expr = Self::CONTRACTION_EXPR.with(|v| v.clone());
664
665        self.condense_expr(&expr, |_| {})
666    }
667}
668
669/// Creates functions necessary to implement [`TokenStringExt]` on a document.
670macro_rules! create_fns_on_doc {
671    ($thing:ident) => {
672        paste! {
673            fn [< first_ $thing >](&self) -> Option<&Token> {
674                self.tokens.[< first_ $thing >]()
675            }
676
677            fn [< last_ $thing >](&self) -> Option<&Token> {
678                self.tokens.[< last_ $thing >]()
679            }
680
681            fn [< last_ $thing _index>](&self) -> Option<usize> {
682                self.tokens.[< last_ $thing _index >]()
683            }
684
685            fn [<iter_ $thing _indices>](&self) -> impl DoubleEndedIterator<Item = usize> + '_ {
686                self.tokens.[< iter_ $thing _indices >]()
687            }
688
689            fn [<iter_ $thing s>](&self) -> impl Iterator<Item = &Token> + '_ {
690                self.tokens.[< iter_ $thing s >]()
691            }
692        }
693    };
694}
695
696impl TokenStringExt for Document {
697    create_fns_on_doc!(adjective);
698    create_fns_on_doc!(apostrophe);
699    create_fns_on_doc!(at);
700    create_fns_on_doc!(chunk_terminator);
701    create_fns_on_doc!(comma);
702    create_fns_on_doc!(conjunction);
703    create_fns_on_doc!(currency);
704    create_fns_on_doc!(ellipsis);
705    create_fns_on_doc!(hostname);
706    create_fns_on_doc!(likely_homograph);
707    create_fns_on_doc!(noun);
708    create_fns_on_doc!(number);
709    create_fns_on_doc!(paragraph_break);
710    create_fns_on_doc!(pipe);
711    create_fns_on_doc!(preposition);
712    create_fns_on_doc!(punctuation);
713    create_fns_on_doc!(quote);
714    create_fns_on_doc!(sentence_terminator);
715    create_fns_on_doc!(space);
716    create_fns_on_doc!(unlintable);
717    create_fns_on_doc!(verb);
718    create_fns_on_doc!(word);
719    create_fns_on_doc!(word_like);
720
721    fn first_sentence_word(&self) -> Option<&Token> {
722        self.tokens.first_sentence_word()
723    }
724
725    fn first_non_whitespace(&self) -> Option<&Token> {
726        self.tokens.first_non_whitespace()
727    }
728
729    fn span(&self) -> Option<Span<char>> {
730        self.tokens.span()
731    }
732
733    fn iter_linking_verb_indices(&self) -> impl Iterator<Item = usize> + '_ {
734        self.tokens.iter_linking_verb_indices()
735    }
736
737    fn iter_linking_verbs(&self) -> impl Iterator<Item = &Token> + '_ {
738        self.tokens.iter_linking_verbs()
739    }
740
741    fn iter_chunks(&self) -> impl Iterator<Item = &'_ [Token]> + '_ {
742        self.tokens.iter_chunks()
743    }
744
745    fn iter_paragraphs(&self) -> impl Iterator<Item = &'_ [Token]> + '_ {
746        self.tokens.iter_paragraphs()
747    }
748
749    fn iter_sentences(&self) -> impl Iterator<Item = &'_ [Token]> + '_ {
750        self.tokens.iter_sentences()
751    }
752
753    fn iter_sentences_mut(&mut self) -> impl Iterator<Item = &'_ mut [Token]> + '_ {
754        self.tokens.iter_sentences_mut()
755    }
756}
757
758impl Display for Document {
759    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
760        for token in &self.tokens {
761            write!(f, "{}", self.get_span_content_str(&token.span))?;
762        }
763
764        Ok(())
765    }
766}
767
768#[cfg(test)]
769mod tests {
770    use itertools::Itertools;
771
772    use super::Document;
773    use crate::{Span, parsers::MarkdownOptions};
774
775    fn assert_condensed_contractions(text: &str, final_tok_count: usize) {
776        let document = Document::new_plain_english_curated(text);
777
778        assert_eq!(document.tokens.len(), final_tok_count);
779
780        let document = Document::new_markdown_curated(text, MarkdownOptions::default());
781
782        assert_eq!(document.tokens.len(), final_tok_count);
783    }
784
785    #[test]
786    fn simple_contraction() {
787        assert_condensed_contractions("isn't", 1);
788    }
789
790    #[test]
791    fn simple_contraction2() {
792        assert_condensed_contractions("wasn't", 1);
793    }
794
795    #[test]
796    fn simple_contraction3() {
797        assert_condensed_contractions("There's", 1);
798    }
799
800    #[test]
801    fn medium_contraction() {
802        assert_condensed_contractions("isn't wasn't", 3);
803    }
804
805    #[test]
806    fn medium_contraction2() {
807        assert_condensed_contractions("There's no way", 5);
808    }
809
810    #[test]
811    fn selects_token_at_char_index() {
812        let text = "There were three little pigs. They built three little homes.";
813        let document = Document::new_plain_english_curated(text);
814
815        let got = document.get_token_at_char_index(19).unwrap();
816
817        assert!(got.kind.is_word());
818        assert_eq!(got.span, Span::new(17, 23));
819    }
820
821    fn assert_token_count(source: &str, count: usize) {
822        let document = Document::new_plain_english_curated(source);
823
824        dbg!(document.tokens().map(|t| t.kind.clone()).collect_vec());
825        assert_eq!(document.tokens.len(), count);
826    }
827
828    #[test]
829    fn condenses_number_suffixes() {
830        assert_token_count("1st", 1);
831        assert_token_count("This is the 2nd test", 9);
832        assert_token_count("This is the 3rd test", 9);
833        assert_token_count(
834            "It works even with weird capitalization like this: 600nD",
835            18,
836        );
837    }
838
839    #[test]
840    fn condenses_ie() {
841        assert_token_count("There is a thing (i.e. that one)", 15);
842        assert_token_count("We are trying to condense \"i.e.\"", 13);
843        assert_token_count(r#"Condenses words like "i.e.", "e.g." and "N.S.A.""#, 20);
844    }
845
846    #[test]
847    fn condenses_eg() {
848        assert_token_count("We are trying to condense \"e.g.\"", 13);
849        assert_token_count(r#"Condenses words like "i.e.", "e.g." and "N.S.A.""#, 20);
850    }
851
852    #[test]
853    fn condenses_nsa() {
854        assert_token_count(r#"Condenses words like "i.e.", "e.g." and "N.S.A.""#, 20);
855    }
856
857    #[test]
858    fn parses_ellipsis() {
859        assert_token_count("...", 1);
860    }
861
862    #[test]
863    fn parses_long_ellipsis() {
864        assert_token_count(".....", 1);
865    }
866
867    #[test]
868    fn parses_short_ellipsis() {
869        assert_token_count("..", 1);
870    }
871
872    #[test]
873    fn selects_token_at_offset() {
874        let doc = Document::new_plain_english_curated("Foo bar baz");
875
876        let tok = doc.get_token_offset(1, -1).unwrap();
877
878        assert_eq!(tok.span, Span::new(0, 3));
879    }
880
881    #[test]
882    fn cant_select_token_before_start() {
883        let doc = Document::new_plain_english_curated("Foo bar baz");
884
885        let tok = doc.get_token_offset(0, -1);
886
887        assert!(tok.is_none());
888    }
889
890    #[test]
891    fn select_next_word_pos_offset() {
892        let doc = Document::new_plain_english_curated("Foo bar baz");
893
894        let bar = doc.get_next_word_from_offset(0, 1).unwrap();
895        let bar = doc.get_span_content(&bar.span);
896        assert_eq!(bar, ['b', 'a', 'r']);
897    }
898
899    #[test]
900    fn select_next_word_neg_offset() {
901        let doc = Document::new_plain_english_curated("Foo bar baz");
902
903        let bar = doc.get_next_word_from_offset(2, -1).unwrap();
904        let bar = doc.get_span_content(&bar.span);
905        assert_eq!(bar, ['F', 'o', 'o']);
906    }
907
908    #[test]
909    fn cant_select_next_word_not_from_whitespace() {
910        let doc = Document::new_plain_english_curated("Foo bar baz");
911
912        let tok = doc.get_next_word_from_offset(0, 2);
913
914        assert!(tok.is_none());
915    }
916
917    #[test]
918    fn cant_select_next_word_before_start() {
919        let doc = Document::new_plain_english_curated("Foo bar baz");
920
921        let tok = doc.get_next_word_from_offset(0, -1);
922
923        assert!(tok.is_none());
924    }
925
926    #[test]
927    fn cant_select_next_word_with_punctuation_instead_of_whitespace() {
928        let doc = Document::new_plain_english_curated("Foo, bar, baz");
929
930        let tok = doc.get_next_word_from_offset(0, 1);
931
932        assert!(tok.is_none());
933    }
934
935    #[test]
936    fn cant_select_next_word_with_punctuation_after_whitespace() {
937        let doc = Document::new_plain_english_curated("Foo \"bar\", baz");
938
939        let tok = doc.get_next_word_from_offset(0, 1);
940
941        assert!(tok.is_none());
942    }
943
944    #[test]
945    fn condenses_filename_extensions() {
946        let doc = Document::new_plain_english_curated(".c and .exe and .js");
947        assert!(doc.tokens[0].kind.is_unlintable());
948        assert!(doc.tokens[4].kind.is_unlintable());
949        assert!(doc.tokens[8].kind.is_unlintable());
950    }
951
952    #[test]
953    fn condense_filename_extension_ok_at_start_and_end() {
954        let doc = Document::new_plain_english_curated(".c and .EXE");
955        assert!(doc.tokens.len() == 5);
956        assert!(doc.tokens[0].kind.is_unlintable());
957        assert!(doc.tokens[4].kind.is_unlintable());
958    }
959
960    #[test]
961    fn doesnt_condense_filename_extensions_with_mixed_case() {
962        let doc = Document::new_plain_english_curated(".c and .Exe");
963        assert!(doc.tokens.len() == 6);
964        assert!(doc.tokens[0].kind.is_unlintable());
965        assert!(doc.tokens[4].kind.is_punctuation());
966        assert!(doc.tokens[5].kind.is_word());
967    }
968
969    #[test]
970    fn doesnt_condense_filename_extensions_with_non_letters() {
971        let doc = Document::new_plain_english_curated(".COM and .C0M");
972        assert!(doc.tokens.len() == 6);
973        assert!(doc.tokens[0].kind.is_unlintable());
974        assert!(doc.tokens[4].kind.is_punctuation());
975        assert!(doc.tokens[5].kind.is_word());
976    }
977
978    #[test]
979    fn doesnt_condense_filename_extensions_longer_than_three() {
980        let doc = Document::new_plain_english_curated(".dll and .dlls");
981        assert!(doc.tokens.len() == 6);
982        assert!(doc.tokens[0].kind.is_unlintable());
983        assert!(doc.tokens[4].kind.is_punctuation());
984        assert!(doc.tokens[5].kind.is_word());
985    }
986
987    #[test]
988    fn condense_filename_extension_in_parens() {
989        let doc = Document::new_plain_english_curated(
990            "true for the manual installation when trying to run the executable(.exe) after a manual download",
991        );
992        assert!(doc.tokens.len() > 23);
993        assert!(doc.tokens[21].kind.is_open_round());
994        assert!(doc.tokens[22].kind.is_unlintable());
995        assert!(doc.tokens[23].kind.is_close_round());
996    }
997}