use crate::{
generator::Generator,
parser::{Item, ItemC},
};
#[derive(Debug, Clone)]
pub enum Tag<'a, C: TagConvertor<'a> + ?Sized> {
Fg(C::Color),
Bg(C::Color),
Modifier(C::Modifier),
Custom(C::Custom),
}
pub type TagG<'a, G> = Tag<'a, <G as Generator<'a>>::Convertor>;
pub trait TagConvertor<'a> {
type Color;
type Modifier;
type Custom;
fn parse_color(&mut self, s: &str) -> Option<Self::Color>;
fn parse_modifier(&mut self, s: &str) -> Option<Self::Modifier>;
fn parse_custom_tag(&mut self, s: &str) -> Option<Self::Custom>;
fn parse_built_in_tag(&mut self, s: &str) -> Option<Tag<'a, Self>> {
let mut ty_value = s.split(':');
let mut ty = ty_value.next()?;
let value = ty_value.next().unwrap_or_else(|| {
let value = ty;
ty = "";
value
});
if ty_value.next().is_some() {
return None;
}
Some(match ty {
"fg" => Tag::Fg(self.parse_color(value)?),
"bg" => Tag::Bg(self.parse_color(value)?),
"mod" => Tag::Modifier(self.parse_modifier(value)?),
"" => {
if let Some(color) = self.parse_color(value) {
Tag::Fg(color)
} else if let Some(modifier) = self.parse_modifier(value) {
Tag::Modifier(modifier)
} else {
return None;
}
}
_ => return None,
})
}
fn convert_tag(&mut self, s: &'a str) -> Option<Tag<'a, Self>> {
self.parse_custom_tag(s)
.map(Tag::Custom)
.or_else(|| self.parse_built_in_tag(s))
}
fn convert_item(&mut self, item: Item<'a>) -> ItemC<'a, Self> {
match item {
Item::PlainText(pt) => Item::PlainText(pt),
Item::Element(spans, items) => {
let tags = spans
.into_iter()
.filter_map(|span| self.convert_tag(span.fragment()))
.collect();
let subitems = self.convert_line(items);
Item::Element(tags, subitems)
}
}
}
fn convert_line(&mut self, items: Vec<Item<'a>>) -> Vec<ItemC<'a, Self>> {
items.into_iter().map(|item| self.convert_item(item)).collect()
}
fn convert_ast(&mut self, ast: Vec<Vec<Item<'a>>>) -> Vec<Vec<ItemC<'a, Self>>> {
ast.into_iter().map(|line| self.convert_line(line)).collect()
}
}