1use regex::Regex;
5
6use super::{Quote, RegexCache, Segment, Shape, TypeRegistry, shape_of, template};
7use crate::{Problem, Spanned, text};
8
9#[derive(Debug, Clone)]
11pub struct FormatVariant {
12 pub shape: Shape,
14 pub example: String,
16}
17
18#[derive(Debug, Clone)]
21pub struct Format {
22 pub shape: Option<Shape>,
24 pub variants: Vec<(String, FormatVariant)>,
26 pub key: Option<String>,
28 pub prohibited: Vec<Prohibition>,
30 pub example: Option<String>,
32 pub raw: Spanned,
34 pub patched: bool,
37}
38
39#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct Captured {
43 pub key: String,
45 pub start: usize,
47}
48
49pub fn captured(shape: &Shape, name: &str, text: &str) -> Option<Captured> {
51 let caps = shape.captures(text)?;
52 Some(Captured {
53 key: caps.name(name)?.as_str().to_string(),
54 start: caps.get(0).map_or(0, |m| m.start()),
55 })
56}
57
58#[derive(Debug, Clone, PartialEq, Eq)]
60pub enum FormatMatch {
61 Ok(Option<Captured>),
63 Fail(String),
65 Refused(String),
67}
68
69impl Format {
70 #[must_use]
74 pub fn read_with(&self, read: &dyn Fn(&str) -> String) -> Format {
75 Format {
76 shape: self.shape.as_ref().map(|s| s.read_with(read)),
77 variants: self
78 .variants
79 .iter()
80 .map(|(name, v)| {
81 (
82 name.clone(),
83 FormatVariant {
84 shape: v.shape.read_with(read),
85 example: v.example.clone(),
86 },
87 )
88 })
89 .collect(),
90 ..self.clone()
91 }
92 }
93
94 pub fn examples(&self) -> Vec<&str> {
96 match &self.example {
97 Some(e) => vec![e.as_str()],
98 None => self
99 .variants
100 .iter()
101 .map(|(_, v)| v.example.as_str())
102 .collect(),
103 }
104 }
105
106 pub(crate) fn shapes(&self) -> impl Iterator<Item = (Option<&str>, &Shape)> {
109 self.shape.iter().map(|s| (None, s)).chain(
110 self.variants
111 .iter()
112 .map(|(name, v)| (Some(name.as_str()), &v.shape)),
113 )
114 }
115
116 pub fn reach(&self, text: &str) -> usize {
119 self.shapes().map(|(_, s)| s.reach(text)).max().unwrap_or(0)
120 }
121
122 pub(super) fn uses_any(&self, types: &[&str]) -> bool {
124 self.hole_types().any(|ty| types.contains(&ty))
125 }
126
127 pub(super) fn uses<'t>(&self, types: &[&'t str]) -> Vec<&'t str> {
130 let mut used = Vec::new();
131 for ty in self.hole_types() {
132 if let Some(&name) = types.iter().find(|n| **n == ty)
133 && !used.contains(&name)
134 {
135 used.push(name);
136 }
137 }
138 used
139 }
140
141 fn hole_types(&self) -> impl Iterator<Item = &str> {
143 self.shapes()
144 .filter_map(|(_, shape)| match shape {
145 Shape::Template(t) => Some(t),
146 _ => None,
147 })
148 .flat_map(|t| t.segments.iter())
149 .filter_map(|s| match s {
150 Segment::Hole { ty, .. } => Some(ty.as_str()),
151 Segment::Literal(_) => None,
152 })
153 }
154
155 pub fn first_example(&self) -> &str {
157 self.example
158 .as_deref()
159 .or_else(|| self.variants.first().map(|(_, v)| v.example.as_str()))
160 .unwrap_or("")
161 }
162
163 pub fn check(&self, text: &str) -> FormatMatch {
171 self.check_as(text, "line")
172 }
173
174 pub fn check_as(&self, text: &str, noun: &str) -> FormatMatch {
176 self.check_masked(text, text, noun)
177 }
178
179 pub fn check_masked(&self, text: &str, masked: &str, noun: &str) -> FormatMatch {
184 self.check_quoting(text, masked, noun, &Quote::same(text))
185 }
186
187 pub fn check_quoting(
190 &self,
191 text: &str,
192 masked: &str,
193 noun: &str,
194 quote: &Quote<'_>,
195 ) -> FormatMatch {
196 let (shape, example) = match self.matching_quoting(text, noun, quote) {
197 Ok(m) => m,
198 Err(reason) => return FormatMatch::Fail(reason),
199 };
200 if let Some(reason) =
201 refused_quoting(text, masked, &self.prohibited, noun, Some(example), quote)
202 {
203 return FormatMatch::Refused(reason);
204 }
205 FormatMatch::Ok(self.key.as_ref().and_then(|k| captured(shape, k, text)))
206 }
207
208 pub fn shape_for(&self, text: &str) -> Option<(&Shape, &str)> {
211 match &self.shape {
212 Some(shape) => shape
213 .matches(text, |_| None)
214 .then(|| (shape, self.example.as_deref().unwrap_or(""))),
215 None => self
216 .variants
217 .iter()
218 .find(|(_, v)| v.shape.matches(text, |_| None))
219 .map(|(_, v)| (&v.shape, v.example.as_str())),
220 }
221 }
222
223 pub fn conforms(&self, text: &str) -> bool {
225 self.conforms_masked(text, text)
226 }
227
228 pub fn conforms_masked(&self, text: &str, masked: &str) -> bool {
230 self.shape_for(text).is_some()
231 && !self.prohibited.iter().any(|b| b.pattern.is_match(masked))
232 }
233
234 pub fn matching(&self, text: &str) -> std::result::Result<(&Shape, &str), String> {
239 self.matching_as(text, "line")
240 }
241
242 pub fn matching_as(
244 &self,
245 text: &str,
246 noun: &str,
247 ) -> std::result::Result<(&Shape, &str), String> {
248 self.matching_quoting(text, noun, &Quote::same(text))
249 }
250
251 pub fn matching_quoting(
254 &self,
255 text: &str,
256 noun: &str,
257 quote: &Quote<'_>,
258 ) -> std::result::Result<(&Shape, &str), String> {
259 if let Some(found) = self.shape_for(text) {
260 return Ok(found);
261 }
262 if let Some(shape) = &self.shape {
263 return Err(format!(
264 "{}{}",
265 shape.failure_quoting(text, quote),
266 reads(noun, self.example.as_deref(), " or ")
267 ));
268 }
269 let reach: Vec<usize> = self
270 .variants
271 .iter()
272 .map(|(_, v)| v.shape.reach(text))
273 .collect();
274 let best = reach.iter().copied().max().unwrap_or(0);
275 let at: Vec<&(String, FormatVariant)> = self
276 .variants
277 .iter()
278 .zip(&reach)
279 .filter(|(_, r)| **r == best)
280 .map(|(v, _)| v)
281 .collect();
282 match at.as_slice() {
283 [] => Err("has no variants to match".into()),
284 [(name, v)] => Err(format!(
285 "does not match the `{name}` form: it {}{}",
286 v.shape.failure_quoting(text, quote),
287 reads(noun, [v.example.as_str()], " or ")
288 )),
289 many => {
290 let at = if best > 0 {
292 format!(
293 ": each fails at column {}",
294 template::column(quote.text, quote.offset(best))
295 )
296 } else {
297 String::new()
298 };
299 Err(format!(
302 "matches none of the forms {}{at}{}",
303 text::code_list(many.iter().map(|(n, _)| n), ", "),
304 reads(noun, many.iter().map(|(_, v)| v.example.as_str()), " or ")
305 ))
306 }
307 }
308 }
309}
310
311pub fn refused(text: &str, bans: &[Prohibition], example: Option<&str>) -> Option<String> {
319 refused_as(text, bans, "line", example)
320}
321
322pub fn refused_as(
328 text: &str,
329 bans: &[Prohibition],
330 noun: &str,
331 example: Option<&str>,
332) -> Option<String> {
333 refused_masked(text, text, bans, noun, example)
334}
335
336pub fn refused_masked(
344 text: &str,
345 masked: &str,
346 bans: &[Prohibition],
347 noun: &str,
348 example: Option<&str>,
349) -> Option<String> {
350 refused_quoting(text, masked, bans, noun, example, &Quote::same(text))
351}
352
353pub fn refused_quoting(
358 text: &str,
359 masked: &str,
360 bans: &[Prohibition],
361 noun: &str,
362 example: Option<&str>,
363 quote: &Quote<'_>,
364) -> Option<String> {
365 bans.iter().find_map(|ban| {
366 let found = ban.pattern.find(masked)?;
367 let span = if text.len() == masked.len() {
368 let written = quote.text;
369 let start = quote.offset(found.start());
370 let end = written.ceil_char_boundary((quote.at)(found.end()).min(written.len()));
371 &written[start..end.max(start)]
372 } else {
373 found.as_str()
374 };
375 let message = ban.message.trim_end();
376 Some(match example.filter(|e| !e.is_empty()) {
377 Some(e) => {
378 let mut article = text::article(noun).to_string();
379 article[..1].make_ascii_uppercase();
380 format!(
381 "{} is refused: {message} {article} {noun} of this kind reads {}",
382 text::code(span),
383 text::code(e)
384 )
385 }
386 None => format!("{} is refused: {message}", text::code(span)),
387 })
388 })
389}
390
391#[derive(Debug, Clone)]
395pub struct Prohibition {
396 pub pattern: Regex,
398 pub message: String,
400}
401
402pub fn prohibitions(node: &Spanned, regexes: &RegexCache) -> Vec<Prohibition> {
406 node.get("prohibited-patterns")
407 .and_then(|b| b.as_seq())
408 .unwrap_or(&[])
409 .iter()
410 .filter_map(|ban| {
411 let pattern = regexes.get(ban.get("pattern")?.as_str()?).ok()?;
412 let message = ban.get("message")?.as_str()?.to_string();
413 Some(Prohibition { pattern, message })
414 })
415 .collect()
416}
417
418fn format_shape(
421 node: &Spanned,
422 types: &TypeRegistry,
423 regexes: &RegexCache,
424) -> std::result::Result<Shape, Problem> {
425 if node.get("text").is_some_and(|t| t.as_str().is_none()) {
426 return Err(Problem::new("TL_101", "a format's `text` is a string"));
427 }
428 shape_of(node, types, regexes)?.ok_or_else(|| {
430 Problem::new(
431 "TL_105",
432 "a shape is one of `text`, `template` or `pattern`",
433 )
434 })
435}
436
437pub(super) fn lower_format(
443 entry: &Spanned,
444 types: &TypeRegistry,
445 regexes: &RegexCache,
446) -> std::result::Result<Format, Vec<(usize, Problem)>> {
447 let mut problems = Vec::new();
448 let mut variants = Vec::new();
449 if let Some(v) = entry.get("variants") {
450 for (name, variant) in v.as_map().unwrap_or(&[]) {
451 match format_shape(variant, types, regexes) {
452 Ok(shape) => variants.push((
453 name.value.clone(),
454 FormatVariant {
455 shape,
456 example: variant
457 .get("example")
458 .and_then(|d| d.as_str())
459 .unwrap_or_default()
460 .to_string(),
461 },
462 )),
463 Err(e) => problems.push((
464 variant.line,
465 e.prefixed(&format!("variant `{}`: ", name.value)),
466 )),
467 }
468 }
469 }
470 let shape = if entry.get("variants").is_some() {
471 None
472 } else {
473 match format_shape(entry, types, regexes) {
474 Ok(s) => Some(s),
475 Err(e) => {
476 problems.push((entry.line, e));
477 None
478 }
479 }
480 };
481 let example = entry
482 .get("example")
483 .and_then(|d| d.as_str())
484 .map(str::to_string);
485 match (&example, entry.get("variants")) {
488 (Some(_), Some(_)) => problems.push((
489 entry.line,
490 Problem::new(
491 "TL_110",
492 "a format with `variants` has no `example` of its own: each variant's example speaks for its shape",
493 ),
494 )),
495 (None, None) => problems.push((
496 entry.line,
497 Problem::new("TL_40", "a format with one shape carries an `example`"),
498 )),
499 _ => {}
500 }
501 let format = Format {
502 shape,
503 variants,
504 key: entry
505 .get("key")
506 .and_then(|k| k.as_str())
507 .map(str::to_string),
508 prohibited: prohibitions(entry, regexes),
509 example,
510 raw: entry.clone(),
511 patched: false,
512 };
513 if let Some(k) = &format.key {
514 for (name, s) in format.shapes() {
515 if !s.has_group(k) {
516 let whose =
517 name.map_or_else(|| "the shape".to_string(), |n| format!("variant `{n}`"));
518 problems.push((
519 entry.line,
520 Problem::new(
521 "TL_31",
522 format!("`key` `{k}` names no hole or named group of {whose}"),
523 ),
524 ));
525 }
526 }
527 }
528 if !problems.is_empty() {
529 return Err(problems);
530 }
531 Ok(format)
532}
533
534pub(crate) fn reads<'a>(
538 noun: &str,
539 examples: impl IntoIterator<Item = &'a str>,
540 sep: &str,
541) -> String {
542 let shown: Vec<String> = examples
543 .into_iter()
544 .filter(|e| !e.is_empty())
545 .map(text::code)
546 .collect();
547 if shown.is_empty() {
548 return String::new();
549 }
550 format!(
551 "; {} {noun} of this kind reads {}",
552 text::article(noun),
553 shown.join(sep)
554 )
555}