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
use std::fmt::Display;

use itertools::Itertools;

use crate::{
    linting::{LintSet, Suggestion},
    parsing::{lex_to_end, lex_to_end_md},
    run_lint_set,
    span::Span,
    Dictionary, FatToken, Lint,
    Punctuation::{self},
    Token, TokenKind,
};

pub struct Document {
    source: Vec<char>,
    tokens: Vec<Token>,
    markdown: bool,
}

impl Document {
    // Lexes and parses text to produce a document.
    //
    // Choosing to parse with markdown may have a performance penalty
    pub fn new(text: &str, markdown: bool) -> Self {
        let source: Vec<_> = text.chars().collect();

        let mut doc = Self {
            source,
            tokens: Vec::new(),
            markdown,
        };
        doc.parse();

        doc
    }

    /// Re-parse important language constructs.
    ///
    /// Should be run after every change to the underlying [`Self::source`].
    fn parse(&mut self) {
        if self.markdown {
            self.tokens = lex_to_end_md(&self.source);
        } else {
            self.tokens = lex_to_end(&self.source);
        }

        self.match_quotes();
    }

    pub fn run_lint_set(&self, lint_set: &LintSet, dictionary: &Dictionary) -> Vec<Lint> {
        run_lint_set(lint_set, self, dictionary)
    }

    pub fn iter_quote_indices(&self) -> impl Iterator<Item = usize> + '_ {
        self.tokens.iter().enumerate().filter_map(|(idx, token)| {
            if let TokenKind::Punctuation(Punctuation::Quote(_)) = &token.kind {
                Some(idx)
            } else {
                None
            }
        })
    }

    pub fn iter_quotes(&self) -> impl Iterator<Item = Token> + '_ {
        self.iter_quote_indices().map(|idx| self.tokens[idx])
    }

    /// Searches for quotation marks and fills the [`Punctuation::Quote::twin_loc`] field.
    /// This is on a best effort basis.
    ///
    /// Current algorithm is very basic and could use some work.
    fn match_quotes(&mut self) {
        let quote_indices: Vec<usize> = self.iter_quote_indices().collect();

        for i in 0..quote_indices.len() / 2 {
            let a_i = quote_indices[i * 2];
            let b_i = quote_indices[i * 2 + 1];

            {
                let a = self.tokens[a_i].kind.as_mut_quote().unwrap();
                a.twin_loc = Some(b_i);
            }

            {
                let b = self.tokens[b_i].kind.as_mut_quote().unwrap();
                b.twin_loc = Some(a_i);
            }
        }
    }

    pub fn tokens(&self) -> impl Iterator<Item = Token> + '_ {
        self.tokens.iter().copied()
    }

    pub fn fat_tokens(&self) -> impl Iterator<Item = FatToken> + '_ {
        self.tokens().map(|token| token.to_fat(&self.source))
    }

    /// Iterate over the locations of the sentence terminators in the document.
    fn sentence_terminators(&self) -> impl Iterator<Item = usize> + '_ {
        self.tokens.iter().enumerate().filter_map(|(index, token)| {
            if let Token {
                kind: TokenKind::Punctuation(punct),
                ..
            } = token
            {
                if is_sentence_terminator(punct) {
                    Some(index)
                } else {
                    None
                }
            } else {
                None
            }
        })
    }

    pub fn sentences(&self) -> impl Iterator<Item = &'_ [Token]> + '_ {
        let first_sentence = self
            .sentence_terminators()
            .next()
            .map(|first_term| &self.tokens[0..=first_term]);

        let rest = self
            .sentence_terminators()
            .tuple_windows()
            .map(move |(a, b)| &self.tokens[a + 1..=b]);

        first_sentence.into_iter().chain(rest)
    }

    /** Returns all tokens whose `kind` is [`Punctuation::Word`] */
    pub fn words(&self) -> impl Iterator<Item = Token> + '_ {
        self.tokens
            .iter()
            .filter(|token| token.kind.is_word())
            .cloned()
    }

    pub fn get_span_content(&self, span: Span) -> &[char] {
        span.get_content(&self.source)
    }

    pub fn get_span_content_str(&self, span: Span) -> String {
        String::from_iter(self.get_span_content(span))
    }

    pub fn get_full_string(&self) -> String {
        self.get_span_content_str(Span {
            start: 0,
            end: self.source.len(),
        })
    }

    pub fn apply_suggestion(&mut self, suggestion: &Suggestion, span: Span) {
        match suggestion {
            Suggestion::ReplaceWith(chars) => {
                // Avoid allocation if possible
                if chars.len() == span.len() {
                    for (index, c) in chars.iter().enumerate() {
                        self.source[index + span.start] = *c
                    }
                } else {
                    let popped = self.source.split_off(span.start);

                    self.source.extend(chars);
                    self.source.extend(popped.into_iter().skip(span.len()));
                }
            }
        }

        self.parse();
    }
}

impl Display for Document {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for token in &self.tokens {
            write!(f, "{}", self.get_span_content_str(token.span))?;
        }

        Ok(())
    }
}

fn is_sentence_terminator(punctuation: &Punctuation) -> bool {
    [
        Punctuation::Period,
        Punctuation::Bang,
        Punctuation::Question,
    ]
    .contains(punctuation)
}

#[cfg(test)]
mod tests {
    use super::Document;
    use crate::Token;

    impl Document {
        fn from_raw_parts(source: Vec<char>, tokens: Vec<Token>, markdown: bool) -> Self {
            Self {
                source,
                tokens,
                markdown,
            }
        }
    }

    #[test]
    fn parses_sentences_correctly() {
        let text = "There were three little pigs. They built three little homes.";
        let document = Document::new(text, false);

        let mut sentence_strs = vec![];

        for sentence in document.sentences() {
            sentence_strs.push(
                Document::from_raw_parts(document.source.clone(), sentence.to_vec(), false)
                    .to_string(),
            );
        }

        assert_eq!(
            sentence_strs,
            vec![
                "There were three little pigs.",
                " They built three little homes."
            ]
        )
    }
}