1use 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#[allow(clippy::derive_partial_eq_without_eq)]
15#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
16#[non_exhaustive]
17pub struct DetectedLanguage {
18 pub code: String,
20 #[cfg(feature = "unstable")]
22 pub confidence: Option<f64>,
23 pub name: String,
25 #[cfg(feature = "unstable")]
27 pub source: Option<String>,
28}
29
30#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
32#[serde(rename_all = "camelCase")]
33#[non_exhaustive]
34pub struct LanguageResponse {
35 pub code: String,
37 pub detected_language: DetectedLanguage,
39 pub name: String,
41}
42
43#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
45#[non_exhaustive]
46pub struct Context {
47 pub length: usize,
49 pub offset: usize,
51 pub text: String,
53}
54
55#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
57#[non_exhaustive]
58pub struct MoreContext {
59 pub line_number: usize,
61 pub line_offset: usize,
63}
64
65#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
67#[non_exhaustive]
68pub struct Replacement {
69 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#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
87#[non_exhaustive]
88pub struct Category {
89 pub id: String,
91 pub name: String,
93}
94
95#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
97#[non_exhaustive]
98pub struct Url {
99 pub value: String,
101}
102
103#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
105#[serde(rename_all = "camelCase")]
106#[non_exhaustive]
107pub struct Rule {
108 pub category: Category,
110 pub description: String,
112 pub id: String,
114 #[cfg(feature = "unstable")]
116 pub is_premium: Option<bool>,
117 pub issue_type: String,
119 #[cfg(feature = "unstable")]
121 pub source_file: Option<String>,
122 pub sub_id: Option<String>,
124 pub urls: Option<Vec<Url>>,
126}
127
128#[derive(PartialEq, Eq, Clone, Debug, Deserialize, Serialize)]
130#[serde(rename_all = "camelCase")]
131#[non_exhaustive]
132pub struct Type {
133 pub type_name: String,
135}
136
137#[derive(PartialEq, Eq, Clone, Debug, Deserialize, Serialize)]
139#[serde(rename_all = "camelCase")]
140#[non_exhaustive]
141pub struct Match {
142 pub context: Context,
144 #[cfg(feature = "unstable")]
147 pub context_for_sure_match: isize,
148 #[cfg(feature = "unstable")]
151 pub ignore_for_incomplete_sentence: bool,
152 pub length: usize,
154 pub message: String,
156 #[serde(skip_serializing_if = "Option::is_none")]
158 pub more_context: Option<MoreContext>,
159 pub offset: usize,
161 pub replacements: Vec<Replacement>,
163 pub rule: Rule,
165 pub sentence: String,
167 pub short_message: String,
169 #[cfg(feature = "unstable")]
171 #[serde(rename = "type")]
172 pub type_: Type,
173}
174
175#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
177#[serde(rename_all = "camelCase")]
178#[non_exhaustive]
179pub struct Software {
180 pub api_version: usize,
182 pub build_date: String,
184 pub name: String,
186 pub premium: bool,
188 #[cfg(feature = "unstable")]
190 pub premium_hint: Option<String>,
191 pub status: String,
194 pub version: String,
196}
197
198#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
200#[serde(rename_all = "camelCase")]
201#[non_exhaustive]
202pub struct Warnings {
203 pub incomplete_results: bool,
205}
206
207#[derive(Clone, PartialEq, Debug, Deserialize, Serialize)]
209#[serde(rename_all = "camelCase")]
210#[non_exhaustive]
211pub struct Response {
212 pub language: LanguageResponse,
214 pub matches: Vec<Match>,
216 #[cfg(feature = "unstable")]
218 pub sentence_ranges: Option<Vec<[usize; 2]>>,
219 pub software: Software,
221 #[cfg(feature = "unstable")]
223 pub warnings: Option<Warnings>,
224}
225
226impl Response {
227 pub fn iter_matches(&self) -> std::slice::Iter<'_, Match> {
229 self.matches.iter()
230 }
231
232 pub fn iter_matches_mut(&mut self) -> std::slice::IterMut<'_, Match> {
234 self.matches.iter_mut()
235 }
236
237 #[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 #[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#[derive(Debug, Clone, PartialEq, IntoStatic)]
331pub struct ResponseWithContext<'source> {
332 pub text: Cow<'source, str>,
334 pub response: Response,
336 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 #[must_use]
350 pub fn new(text: Cow<'source, str>, response: Response) -> Self {
351 let text_length = text.chars().count();
352
353 Self {
355 text,
356 response,
357 text_length,
358 }
359 }
360
361 pub fn iter_matches(&'source self) -> std::slice::Iter<'source, Match> {
363 self.response.iter_matches()
364 }
365
366 pub fn iter_matches_mut(&mut self) -> std::slice::IterMut<'_, Match> {
368 self.response.iter_matches_mut()
369 }
370
371 #[must_use]
374 pub fn iter_match_positions(&self) -> MatchPositions<'_, '_, std::slice::Iter<'_, Match>> {
375 self.into()
376 }
377
378 #[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#[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 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}