Skip to main content

languagetool_rust/api/check/
responses.rs

1//! Structures for `check` responses.
2
3use std::{borrow::Cow, marker::PhantomData, ops::Deref};
4
5#[cfg(feature = "annotate")]
6use annotate_snippets::{
7    display_list::{DisplayList, FormatOptions},
8    snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation},
9};
10use lifetime::IntoStatic;
11use serde::{Deserialize, Serialize};
12
13/// Detected language from check request.
14#[allow(clippy::derive_partial_eq_without_eq)]
15#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
16#[non_exhaustive]
17pub struct DetectedLanguage {
18    /// Language code, e.g., `"sk-SK"` for Slovak.
19    pub code: String,
20    /// Confidence level, from 0 to 1.
21    #[cfg(feature = "unstable")]
22    pub confidence: Option<f64>,
23    /// Language name, e.g., `"Slovak"`.
24    pub name: String,
25    /// Source (file) for the language detection.
26    #[cfg(feature = "unstable")]
27    pub source: Option<String>,
28}
29
30/// Language information in check response.
31#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
32#[serde(rename_all = "camelCase")]
33#[non_exhaustive]
34pub struct LanguageResponse {
35    /// Language code, e.g., `"sk-SK"` for Slovak.
36    pub code: String,
37    /// Detected language from provided request.
38    pub detected_language: DetectedLanguage,
39    /// Language name, e.g., `"Slovak"`.
40    pub name: String,
41}
42
43/// Match context in check response.
44#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
45#[non_exhaustive]
46pub struct Context {
47    /// Length of the match.
48    pub length: usize,
49    /// Char index at which the match starts.
50    pub offset: usize,
51    /// Contextual text around the match.
52    pub text: String,
53}
54
55/// More context, post-processed in check response.
56#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
57#[non_exhaustive]
58pub struct MoreContext {
59    /// Line number where match occurred.
60    pub line_number: usize,
61    /// Char index at which the match starts on the current line.
62    pub line_offset: usize,
63}
64
65/// Possible replacement for a given match in check response.
66#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
67#[non_exhaustive]
68pub struct Replacement {
69    /// Possible replacement value.
70    pub value: String,
71}
72
73impl From<String> for Replacement {
74    fn from(value: String) -> Self {
75        Self { value }
76    }
77}
78
79impl From<&str> for Replacement {
80    fn from(value: &str) -> Self {
81        value.to_string().into()
82    }
83}
84
85/// A rule category.
86#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
87#[non_exhaustive]
88pub struct Category {
89    /// Category id.
90    pub id: String,
91    /// Category name.
92    pub name: String,
93}
94
95/// A possible url of a rule in a check response.
96#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
97#[non_exhaustive]
98pub struct Url {
99    /// Url value.
100    pub value: String,
101}
102
103/// The rule that was not satisfied in a given match.
104#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
105#[serde(rename_all = "camelCase")]
106#[non_exhaustive]
107pub struct Rule {
108    /// Rule category.
109    pub category: Category,
110    /// Rule description.
111    pub description: String,
112    /// Rule id.
113    pub id: String,
114    /// Indicate if the rule is from the premium API.
115    #[cfg(feature = "unstable")]
116    pub is_premium: Option<bool>,
117    /// Issue type.
118    pub issue_type: String,
119    /// Rule source file.
120    #[cfg(feature = "unstable")]
121    pub source_file: Option<String>,
122    /// Rule sub id.
123    pub sub_id: Option<String>,
124    /// Rule list of urls.
125    pub urls: Option<Vec<Url>>,
126}
127
128/// Type of given match.
129#[derive(PartialEq, Eq, Clone, Debug, Deserialize, Serialize)]
130#[serde(rename_all = "camelCase")]
131#[non_exhaustive]
132pub struct Type {
133    /// Type name.
134    pub type_name: String,
135}
136
137/// Grammatical error match.
138#[derive(PartialEq, Eq, Clone, Debug, Deserialize, Serialize)]
139#[serde(rename_all = "camelCase")]
140#[non_exhaustive]
141pub struct Match {
142    /// Match context.
143    pub context: Context,
144    /// Unknown: please fill a [PR](https://github.com/jeertmans/languagetool-rust/pulls) of your
145    /// know that this attribute is used for.
146    #[cfg(feature = "unstable")]
147    pub context_for_sure_match: isize,
148    /// Unknown: please fill a [PR](https://github.com/jeertmans/languagetool-rust/pulls) of your
149    /// know that this attribute is used for.
150    #[cfg(feature = "unstable")]
151    pub ignore_for_incomplete_sentence: bool,
152    /// Match length.
153    pub length: usize,
154    /// Error message.
155    pub message: String,
156    /// More context to match, post-processed using original text.
157    #[serde(skip_serializing_if = "Option::is_none")]
158    pub more_context: Option<MoreContext>,
159    /// Char index at which the match starts.
160    pub offset: usize,
161    /// List of possible replacements (if applies).
162    pub replacements: Vec<Replacement>,
163    /// Match rule that was not satisfied.
164    pub rule: Rule,
165    /// Sentence in which the error was found.
166    pub sentence: String,
167    /// Short message about the error.
168    pub short_message: String,
169    /// Match type.
170    #[cfg(feature = "unstable")]
171    #[serde(rename = "type")]
172    pub type_: Type,
173}
174
175/// LanguageTool software details.
176#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
177#[serde(rename_all = "camelCase")]
178#[non_exhaustive]
179pub struct Software {
180    /// LanguageTool API version.
181    pub api_version: usize,
182    /// Some information about build date.
183    pub build_date: String,
184    /// Name (should be `"LanguageTool"`).
185    pub name: String,
186    /// Tell whether the server uses premium API or not.
187    pub premium: bool,
188    /// Sentence that indicates if using premium API would find more errors.
189    #[cfg(feature = "unstable")]
190    pub premium_hint: Option<String>,
191    /// Unknown: please fill a [PR](https://github.com/jeertmans/languagetool-rust/pulls) of your
192    /// know that this attribute is used for.
193    pub status: String,
194    /// LanguageTool version.
195    pub version: String,
196}
197
198/// Warnings about check response.
199#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
200#[serde(rename_all = "camelCase")]
201#[non_exhaustive]
202pub struct Warnings {
203    /// Indicate if results are incomplete.
204    pub incomplete_results: bool,
205}
206
207/// LanguageTool POST check response.
208#[derive(Clone, PartialEq, Debug, Deserialize, Serialize)]
209#[serde(rename_all = "camelCase")]
210#[non_exhaustive]
211pub struct Response {
212    /// Language information.
213    pub language: LanguageResponse,
214    /// List of error matches.
215    pub matches: Vec<Match>,
216    /// Ranges ([start, end]) of sentences.
217    #[cfg(feature = "unstable")]
218    pub sentence_ranges: Option<Vec<[usize; 2]>>,
219    /// LanguageTool software information.
220    pub software: Software,
221    /// Possible warnings.
222    #[cfg(feature = "unstable")]
223    pub warnings: Option<Warnings>,
224}
225
226impl Response {
227    /// Return an iterator over matches.
228    pub fn iter_matches(&self) -> std::slice::Iter<'_, Match> {
229        self.matches.iter()
230    }
231
232    /// Return an iterator over mutable matches.
233    pub fn iter_matches_mut(&mut self) -> std::slice::IterMut<'_, Match> {
234        self.matches.iter_mut()
235    }
236
237    /// Creates an annotated string from current response.
238    #[cfg(feature = "annotate")]
239    #[must_use]
240    pub fn annotate(&self, text: &str, origin: Option<&str>, color: bool) -> String {
241        if self.matches.is_empty() {
242            return "No errors were found in provided text".to_string();
243        }
244        let replacements: Vec<_> = self
245            .matches
246            .iter()
247            .map(|m| {
248                m.replacements.iter().fold(String::new(), |mut acc, r| {
249                    if !acc.is_empty() {
250                        acc.push_str(", ");
251                    }
252                    acc.push_str(&r.value);
253                    acc
254                })
255            })
256            .collect();
257
258        let snippets = self.matches.iter().zip(replacements.iter()).map(|(m, r)| {
259            Snippet {
260                title: Some(Annotation {
261                    label: Some(&m.message),
262                    id: Some(&m.rule.id),
263                    annotation_type: AnnotationType::Error,
264                }),
265                footer: vec![],
266                slices: vec![Slice {
267                    source: &m.context.text,
268                    line_start: 1 + text.chars().take(m.offset).filter(|c| *c == '\n').count(),
269                    origin,
270                    fold: true,
271                    annotations: vec![
272                        SourceAnnotation {
273                            label: &m.rule.description,
274                            annotation_type: AnnotationType::Error,
275                            range: (m.context.offset, m.context.offset + m.context.length),
276                        },
277                        SourceAnnotation {
278                            label: r,
279                            annotation_type: AnnotationType::Help,
280                            range: (m.context.offset, m.context.offset + m.context.length),
281                        },
282                    ],
283                }],
284                opt: FormatOptions {
285                    color,
286                    ..Default::default()
287                },
288            }
289        });
290
291        let mut annotation = String::new();
292
293        for snippet in snippets {
294            if !annotation.is_empty() {
295                annotation.push('\n');
296            }
297            annotation.push_str(&DisplayList::from(snippet).to_string());
298        }
299        annotation
300    }
301
302    /// Joins the given [`super::Request`] to the current one.
303    ///
304    /// This is especially useful when a request was split into multiple
305    /// requests.
306    #[must_use]
307    pub fn append(mut self, mut other: Self) -> Self {
308        #[cfg(feature = "unstable")]
309        if let Some(ref mut sr_other) = other.sentence_ranges {
310            match self.sentence_ranges {
311                Some(ref mut sr_self) => {
312                    sr_self.append(sr_other);
313                },
314                None => {
315                    std::mem::swap(&mut self.sentence_ranges, &mut other.sentence_ranges);
316                },
317            }
318        }
319
320        self.matches.append(&mut other.matches);
321
322        self
323    }
324}
325
326/// Check response with additional context.
327///
328/// This structure exists to keep a link between a check response
329/// and the original text that was checked.
330#[derive(Debug, Clone, PartialEq, IntoStatic)]
331pub struct ResponseWithContext<'source> {
332    /// Original text that was checked by LT.
333    pub text: Cow<'source, str>,
334    /// Check response.
335    pub response: Response,
336    /// Text's length.
337    pub text_length: usize,
338}
339
340impl Deref for ResponseWithContext<'_> {
341    type Target = Response;
342    fn deref(&self) -> &Self::Target {
343        &self.response
344    }
345}
346
347impl<'source> ResponseWithContext<'source> {
348    /// Bind a check response with its original text.
349    #[must_use]
350    pub fn new(text: Cow<'source, str>, response: Response) -> Self {
351        let text_length = text.chars().count();
352
353        // Add more context to response
354        Self {
355            text,
356            response,
357            text_length,
358        }
359    }
360
361    /// Return an iterator over matches.
362    pub fn iter_matches(&'source self) -> std::slice::Iter<'source, Match> {
363        self.response.iter_matches()
364    }
365
366    /// Return an iterator over mutable matches.
367    pub fn iter_matches_mut(&mut self) -> std::slice::IterMut<'_, Match> {
368        self.response.iter_matches_mut()
369    }
370
371    /// Return an iterator over matches and corresponding line number and line
372    /// offset.
373    #[must_use]
374    pub fn iter_match_positions(&self) -> MatchPositions<'_, '_, std::slice::Iter<'_, Match>> {
375        self.into()
376    }
377
378    /// Append a check response to the current while
379    /// adjusting the matches' offsets.
380    ///
381    /// This is especially useful when a text was split in multiple requests.
382    #[must_use]
383    pub fn append(mut self, mut other: Self) -> Self {
384        let offset = self.text_length;
385        for m in other.iter_matches_mut() {
386            m.offset += offset;
387        }
388
389        #[cfg(feature = "unstable")]
390        if let Some(ref mut sr_other) = other.response.sentence_ranges {
391            match self.response.sentence_ranges {
392                Some(ref mut sr_self) => {
393                    sr_self.append(sr_other);
394                },
395                None => {
396                    std::mem::swap(
397                        &mut self.response.sentence_ranges,
398                        &mut other.response.sentence_ranges,
399                    );
400                },
401            }
402        }
403
404        self.response.matches.append(&mut other.response.matches);
405
406        self.text.to_mut().push_str(&other.text);
407        self.text_length += other.text_length;
408
409        self
410    }
411}
412
413impl<'source> From<ResponseWithContext<'source>> for Response {
414    fn from(mut resp: ResponseWithContext<'source>) -> Self {
415        for (line_number, line_offset, m) in MatchPositions::new(&resp.text, &mut resp.response) {
416            m.more_context = Some(MoreContext {
417                line_number,
418                line_offset,
419            });
420        }
421
422        resp.response
423    }
424}
425
426/// Iterator over matches and their corresponding line number and line offset.
427#[derive(Clone, Debug)]
428pub struct MatchPositions<'source, 'response, T: Iterator + 'response> {
429    text_chars: std::str::Chars<'source>,
430    matches: T,
431    line_number: usize,
432    line_offset: usize,
433    offset: usize,
434    _marker: PhantomData<&'response ()>,
435}
436
437impl<'source, 'response> MatchPositions<'source, 'response, std::slice::IterMut<'response, Match>> {
438    fn new(text: &'source str, response: &'response mut Response) -> Self {
439        MatchPositions {
440            _marker: Default::default(),
441            text_chars: text.chars(),
442            matches: response.iter_matches_mut(),
443            line_number: 1,
444            line_offset: 0,
445            offset: 0,
446        }
447    }
448}
449
450impl<'source, 'response> From<&'source ResponseWithContext<'source>>
451    for MatchPositions<'source, 'response, std::slice::Iter<'response, Match>>
452where
453    'source: 'response,
454{
455    fn from(response: &'source ResponseWithContext) -> Self {
456        MatchPositions {
457            _marker: Default::default(),
458            text_chars: response.text.chars(),
459            matches: response.iter_matches(),
460            line_number: 1,
461            line_offset: 0,
462            offset: 0,
463        }
464    }
465}
466
467impl<'source, 'response> From<&'source mut ResponseWithContext<'source>>
468    for MatchPositions<'source, 'response, std::slice::IterMut<'response, Match>>
469where
470    'source: 'response,
471{
472    fn from(response: &'source mut ResponseWithContext) -> Self {
473        MatchPositions {
474            _marker: Default::default(),
475            text_chars: response.text.chars(),
476            matches: response.response.iter_matches_mut(),
477            line_number: 1,
478            line_offset: 0,
479            offset: 0,
480        }
481    }
482}
483
484impl<'response, T: Iterator + 'response> MatchPositions<'_, 'response, T> {
485    /// Set the line number to a given value.
486    ///
487    /// By default, the first line number is 1.
488    pub fn set_line_number(mut self, line_number: usize) -> Self {
489        self.line_number = line_number;
490        self
491    }
492
493    fn update_line_number_and_offset(&mut self, m: &Match) {
494        let n = m.offset - self.offset;
495        for _ in 0..n {
496            match self.text_chars.next() {
497                Some('\n') => {
498                    self.line_number += 1;
499                    self.line_offset = 0;
500                },
501                None => {
502                    panic!(
503                        "text is shorter than expected, are you sure this text was the one used \
504                         for the check request?"
505                    )
506                },
507                _ => self.line_offset += 1,
508            }
509        }
510        self.offset = m.offset;
511    }
512}
513
514impl<'source, 'response> Iterator
515    for MatchPositions<'source, 'response, std::slice::Iter<'response, Match>>
516where
517    'response: 'source,
518{
519    type Item = (usize, usize, &'source Match);
520
521    fn next(&mut self) -> Option<Self::Item> {
522        if let Some(m) = self.matches.next() {
523            self.update_line_number_and_offset(m);
524            Some((self.line_number, self.line_offset, m))
525        } else {
526            None
527        }
528    }
529}
530
531impl<'source, 'response> Iterator
532    for MatchPositions<'source, 'response, std::slice::IterMut<'response, Match>>
533where
534    'response: 'source,
535{
536    type Item = (usize, usize, &'source mut Match);
537
538    fn next(&mut self) -> Option<Self::Item> {
539        if let Some(m) = self.matches.next() {
540            self.update_line_number_and_offset(m);
541            Some((self.line_number, self.line_offset, m))
542        } else {
543            None
544        }
545    }
546}