use std::ops::Range;
use super::{FormatRegistry, Unit, captured, nearest};
use crate::{
grammar::{Format, Limit, Shape, row_reading},
markdown,
};
impl Unit {
pub(crate) fn files_under<'a>(&'a self, around: &[Option<&'a str>]) -> Option<&'a str> {
self.key_of.as_deref().or_else(|| nearest(around))
}
pub(crate) fn named_by<'a>(&'a self, around: &[Option<&'a str>]) -> Option<&'a str> {
self.rule_id.as_deref().or_else(|| nearest(around))
}
pub fn hard_max(&self) -> Option<usize> {
self.max.as_ref().and_then(Limit::hard)
}
pub(crate) fn format_in<'f>(&self, formats: &'f FormatRegistry) -> Option<&'f Format> {
formats.get(self.format.as_deref()?)
}
pub(crate) fn bans_in(&self, formats: &FormatRegistry) -> bool {
!self.prohibited_patterns.is_empty()
|| self
.format_in(formats)
.is_some_and(|f| !f.prohibited.is_empty())
}
pub(crate) fn key_in(&self, formats: &FormatRegistry, text: &str) -> Option<String> {
if let Some(shape) = self.matcher() {
return Some(captured(shape, self.key.as_deref()?, text)?.key);
}
let format = self.format_in(formats)?;
let name = self.key.as_ref().or(format.key.as_ref())?;
let (shape, _) = format.shape_for(text)?;
Some(captured(shape, name, text)?.key)
}
pub(crate) fn key_span_in(&self, formats: &FormatRegistry, text: &str) -> Option<Range<usize>> {
let (shape, name) = if let Some(shape) = self.matcher() {
(shape, self.key.as_deref()?)
} else {
let format = self.format_in(formats)?;
let name = self.key.as_ref().or(format.key.as_ref())?;
(format.shape_for(text)?.0, name.as_str())
};
Some(shape.captures(text)?.name(name)?.range())
}
pub(crate) fn fits(
&self,
formats: &FormatRegistry,
text: &str,
value: impl Fn(&str) -> Option<String>,
) -> bool {
match self.matcher() {
Some(shape) => shape.matches(text, value),
None => self
.format_in(formats)
.is_some_and(|f| f.shape_for(text).is_some()),
}
}
pub(crate) fn reach(&self, formats: &FormatRegistry, text: &str) -> usize {
match self.matcher() {
Some(shape) => shape.reach(text),
None => self.format_in(formats).map_or(0, |f| f.reach(text)),
}
}
pub(crate) fn read_text(&self, text: &str) -> String {
self.reading_of(text).text
}
pub(crate) fn reading_of(&self, text: &str) -> markdown::Reading {
self.reader()(text)
}
pub(crate) fn reader(&self) -> fn(&str) -> markdown::Reading {
if self.reads_row {
row_reading
} else if self.reads_prose {
markdown::reading
} else {
markdown::Reading::written
}
}
pub(crate) fn matcher(&self) -> Option<&Shape> {
self.read.as_ref().or(self.shape.as_ref())
}
pub fn example(&self) -> Option<&str> {
self.examples.first().map(String::as_str)
}
pub fn has_shape(&self) -> bool {
self.shape.is_some() || self.format.is_some()
}
pub fn is_counter(&self) -> bool {
self.select.is_some()
&& !self.has_shape()
&& self.key.is_none()
&& self.prohibited_patterns.is_empty()
&& self.blocks.is_none()
&& self.lines.is_none()
&& self.for_each_key_of.is_none()
}
pub fn is_production(&self) -> bool {
self.select.is_none() && self.has_shape()
}
}