1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
use crate::{
generator::Generator,
parser::{Item, ItemC, LSpan},
};
#[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, ty: &str, value: &str) -> Option<Tag<'a, Self>> {
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: LSpan<'a>) -> 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 Some(Tag::Custom(self.parse_custom_tag(s.fragment())?));
}
self.parse_custom_tag(s.fragment())
.map(Tag::Custom)
.or_else(|| self.parse_built_in_tag(ty, value))
}
fn convert_item(&mut self, item: Item<'a>) -> Result<ItemC<'a, Self>, LSpan<'a>> {
match item {
Item::PlainText(pt) => Ok(Item::PlainText(pt)),
Item::Element(spans, items) => {
let mut tags = Vec::with_capacity(spans.len());
for span in spans {
let tag = self.convert_tag(span).ok_or(span)?;
tags.push(tag);
}
let subitems = self.convert_line(items)?;
Ok(Item::Element(tags, subitems))
}
}
}
fn convert_line(&mut self, items: Vec<Item<'a>>) -> Result<Vec<ItemC<'a, Self>>, LSpan<'a>> {
items.into_iter().map(|item| self.convert_item(item)).collect()
}
fn convert(&mut self, ast: Vec<Vec<Item<'a>>>) -> Result<Vec<Vec<ItemC<'a, Self>>>, LSpan<'a>> {
ast.into_iter().map(|line| self.convert_line(line)).collect()
}
}