use itertools::Itertools;
use logos::Lexer;
use crate::{
lexer::{FieldToken, TagToken, Token},
parsing::model::{Field, FieldKind, Link},
};
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Event {
ControlHeader(String),
BoldStart,
BoldEnd,
UnderlineStart,
UnderlineEnd,
ItalicStart,
ItalicEnd,
Align(Alignment),
LiteralStart,
LiteralEnd,
ForegroundColorSet(String),
ForegroundColorUnset,
BackgroundColorSet(String),
BackgroundColorUnset,
Link(Link),
Field(Field),
SectionStart { level: u8 },
SectionReset,
Line(Option<String>),
Newline,
Text(String),
Comment(String),
UnknownTag(String),
}
fn parse_link(tokens: Vec<TagToken>) -> Link {
let mut label = None;
let mut url = String::new();
let mut t_sep = 0;
let mut parts = vec![];
let mut fields = vec![];
for t in tokens {
match t {
TagToken::PipeSeparator => (),
TagToken::Part(p) => {
if t_sep < 2 {
parts.push(p)
} else {
fields.push(p);
}
}
TagToken::TagSeparator => t_sep += 1,
}
}
if !parts.is_empty() {
url = parts.pop().unwrap();
label = parts.pop();
}
Link { label, url, fields }
}
fn parse_field(token: FieldToken) -> Field {
let name: String;
let value: String;
let filter_tag_part = |tag_tokens: Vec<TagToken>| {
tag_tokens
.into_iter()
.filter_map(|t| {
if let TagToken::Part(p) = t {
Some(p)
} else {
None
}
})
.rev() .collect::<Vec<_>>()
};
let kind = match token {
FieldToken::Checkbox(tag_tokens) => {
let mut parts = filter_tag_part(tag_tokens);
name = parts.pop().unwrap_or_default();
value = parts.pop().unwrap_or_default();
let pre_checked = parts.contains(&"*".to_string());
FieldKind::Checkbox { pre_checked }
}
FieldToken::Radio(tag_tokens) => {
let mut parts = filter_tag_part(tag_tokens);
name = parts.pop().unwrap_or_default();
value = parts.pop().unwrap_or_default();
let pre_checked = parts.contains(&"*".to_string());
FieldKind::Radio { pre_checked }
}
FieldToken::Input(tag_tokens) => {
let has_options = tag_tokens
.iter()
.any(|i| matches!(i, &TagToken::PipeSeparator));
let mut parts = filter_tag_part(tag_tokens);
let options = if has_options {
Some(parts.pop().unwrap_or_default())
} else {
None
};
name = parts.pop().unwrap_or_default();
value = parts.pop().unwrap_or_default();
let (hidden, size) = if let Some(options) = options {
let mut hidden = false;
let mut size_buf = String::new();
options.chars().for_each(|c| {
if c == '!' {
hidden = true;
} else if c.is_ascii_digit() {
size_buf.push(c);
}
});
let size = size_buf.parse::<u8>().ok();
(hidden, size)
} else {
(false, None)
};
FieldKind::Input { hidden, size }
}
};
Field { kind, name, value }
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum Alignment {
Default,
Left,
Center,
Right,
}
pub(crate) fn token_to_event(mut lexer: Lexer<Token>) -> impl Iterator<Item = Event> {
let mut stack: Vec<Event> = vec![];
let mut previous_token: Option<Token>;
let mut current_token: Option<Token> = None;
let mut bold = false;
let mut italic = false;
let mut underline = false;
let mut in_literal_mode = false;
let mut fg_set = false;
let mut bg_set = false;
let mut alignment = Alignment::Default;
let mut in_comment = false;
let mut comment_stack = String::new();
let mut in_line = false;
let mut line_stack = String::new();
let mut in_control_header = false;
let mut control_header_stack = String::new();
while let Some(tr) = lexer.next() {
if let Ok(t) = tr {
previous_token = current_token.clone();
current_token = Some(t.clone());
let is_sol = previous_token.is_none() || previous_token == Some(Token::Newline);
if in_comment {
if current_token == Some(Token::Newline) {
in_comment = false;
stack.push(Event::Comment(comment_stack.clone()));
stack.push(Event::Newline);
comment_stack = String::new();
} else {
comment_stack += lexer.slice();
}
} else if in_line {
if current_token == Some(Token::Newline) {
in_line = false;
stack.push(Event::Line(Some(line_stack.clone())));
stack.push(Event::Newline);
line_stack = String::new();
} else {
line_stack += lexer.slice();
}
} else if in_control_header {
if current_token == Some(Token::Newline) {
in_control_header = false;
stack.push(Event::ControlHeader(control_header_stack.clone()));
control_header_stack = String::new();
} else {
control_header_stack += lexer.slice();
}
}
else if in_literal_mode && t == Token::LiteralToggle && is_sol {
in_literal_mode = false;
stack.push(Event::LiteralEnd);
}
else if (in_literal_mode) && t != Token::Newline {
stack.push(Event::Text(lexer.slice().to_string()))
} else {
match t {
Token::ControlHeader => {
if is_sol {
in_control_header = true;
} else {
stack.push(Event::Text(lexer.slice().to_string()));
}
}
Token::BoldToggle => {
if bold {
stack.push(Event::BoldEnd)
} else {
stack.push(Event::BoldStart)
}
bold = !bold;
}
Token::UnderlineToggle => {
if underline {
stack.push(Event::UnderlineEnd)
} else {
stack.push(Event::UnderlineStart)
}
underline = !underline;
}
Token::ItalicToggle => {
if italic {
stack.push(Event::ItalicEnd)
} else {
stack.push(Event::ItalicStart)
}
italic = !italic;
}
Token::AlignDefault => {
let a = Alignment::Default;
if alignment != a {
alignment = a;
stack.push(Event::Align(a))
}
}
Token::AlignLeft => {
let a = Alignment::Left;
if alignment != a {
alignment = a;
stack.push(Event::Align(a))
}
}
Token::AlignCenter => {
let a = Alignment::Center;
if alignment != a {
alignment = a;
stack.push(Event::Align(a))
}
}
Token::AlignRight => {
let a = Alignment::Right;
if alignment != a {
alignment = a;
stack.push(Event::Align(a))
}
}
Token::StyleReset => {
if bold {
bold = false;
stack.push(Event::BoldEnd);
}
if italic {
italic = false;
stack.push(Event::ItalicEnd);
}
if underline {
underline = false;
stack.push(Event::UnderlineEnd);
}
if fg_set {
fg_set = false;
stack.push(Event::ForegroundColorUnset);
}
if bg_set {
bg_set = false;
stack.push(Event::BackgroundColorUnset);
}
if alignment != Alignment::Default {
alignment = Alignment::Default;
stack.push(Event::Align(Alignment::Default));
}
}
Token::LiteralToggle => {
if is_sol {
in_literal_mode = true;
stack.push(Event::LiteralStart);
} else {
stack.push(Event::Newline);
}
}
Token::ColorForegroundSet(s) => {
fg_set = true;
stack.push(Event::ForegroundColorSet(s))
}
Token::ColorForegroundUnset => {
if fg_set {
fg_set = false;
stack.push(Event::ForegroundColorUnset)
}
}
Token::ColorBackgroundSet(s) => {
bg_set = true;
stack.push(Event::BackgroundColorSet(s))
}
Token::ColorBackgroundUnset => {
if bg_set {
bg_set = false;
stack.push(Event::BackgroundColorUnset)
}
}
Token::Link(tag_tokens) => stack.push(Event::Link(parse_link(tag_tokens))),
Token::Field(field_token) => stack.push(Event::Field(parse_field(field_token))),
Token::SectionStart(level) => {
if is_sol {
stack.push(Event::SectionStart { level });
} else {
stack.push(Event::Text(lexer.slice().to_string()));
}
}
Token::SectionEnd => {
if is_sol {
stack.push(Event::SectionReset);
} else {
stack.push(Event::Text(lexer.slice().to_string()));
}
}
Token::Line => {
if is_sol {
in_line = true;
} else {
stack.push(Event::Text(lexer.slice().to_string()));
}
}
Token::Comment => {
if is_sol {
in_comment = true;
} else {
stack.push(Event::Text(lexer.slice().to_string()));
}
}
Token::Escape(c) => stack.push(Event::Text(c.to_string())),
Token::Newline => {
stack.push(Event::Newline);
}
Token::Text(s) => stack.push(Event::Text(s)),
Token::UnknownTag => stack.push(Event::UnknownTag(lexer.slice().to_string())),
}
}
}
}
if in_comment {
stack.push(Event::Comment("".to_string()));
}
if in_line {
stack.push(Event::Line(None));
}
stack.into_iter().coalesce(|a, b| match (a, b) {
(Event::Text(sa), Event::Text(sb)) => Ok(Event::Text(sa + &sb)),
(a, b) => Err((a, b)),
})
}
#[cfg(test)]
mod tests {
use super::*;
use logos::Logos;
#[test]
fn can_eventify_cursed_style_reset_style() {
let mu = include_str!("../tests/cases/cursed/style_reset_style.mu");
let lex = Token::lexer(mu);
let events = token_to_event(lex).collect::<Vec<_>>();
let expected = vec![
Event::BoldStart,
Event::Text("Bold".to_string()),
Event::BoldEnd,
Event::Text("NotBold".to_string()),
Event::BoldStart,
Event::Text("Bold".to_string()),
Event::BoldEnd,
Event::Newline,
];
assert_eq!(expected, events);
}
#[test]
fn can_eventify_cursed_section_newlines() {
let mu = include_str!("../tests/cases/cursed/section_newlines.mu");
let lex = Token::lexer(mu);
let events = token_to_event(lex).collect::<Vec<_>>();
let expected = vec![
Event::SectionStart { level: 1 },
Event::Text("Outputting Formatted Text".to_string()),
Event::Newline,
Event::Newline,
Event::Newline,
Event::SectionStart { level: 15 },
Event::Newline,
Event::Line(Some("∿".to_string())),
Event::Newline,
Event::SectionReset,
Event::Newline,
];
assert_eq!(expected, events);
}
#[test]
fn can_eventify_background() {
let mu = include_str!("../tests/cases/background.mu");
let lex = Token::lexer(mu);
let events = token_to_event(lex).collect::<Vec<_>>();
let expected = vec![
Event::Text("We'll set ".to_string()),
Event::BackgroundColorSet("bbb".to_string()),
Event::Text("background here, unset ".to_string()),
Event::BackgroundColorUnset,
Event::Text(" here.".to_string()),
Event::Newline,
Event::BackgroundColorSet("e2e".to_string()),
Event::Text("This is a full width background.".to_string()),
Event::Newline,
];
assert_eq!(expected, events);
}
#[test]
fn can_eventify_section() {
let mu = include_str!("../tests/cases/section.mu");
let lex = Token::lexer(mu);
let events = token_to_event(lex).collect::<Vec<_>>();
let expected = vec![
Event::SectionStart { level: 1 },
Event::Text("This is a section header".to_string()),
Event::Newline,
Event::Text("and this is some section text".to_string()),
Event::Newline,
Event::Text("this is a > mid sentence section tag, ignored".to_string()),
Event::Newline,
Event::Newline,
Event::SectionReset,
Event::Newline,
Event::Text("and this is some non sectioned text".to_string()),
Event::Newline,
Event::Text("this is a < mid sentence section end tag, ignored".to_string()),
Event::Newline,
Event::SectionReset,
Event::Text(" but this end section tag is honored".to_string()),
Event::Newline,
];
assert_eq!(expected, events);
}
#[test]
fn can_eventify_field_radio() {
let mu = include_str!("../tests/cases/field_radio.mu");
let lex = Token::lexer(mu);
let events = token_to_event(lex).collect::<Vec<_>>();
let expected = vec![
Event::Text("Radio: ".to_string()),
Event::Field(Field {
kind: FieldKind::Radio { pre_checked: false },
name: "color".to_string(),
value: "Red".to_string(),
}),
Event::Text(" red".to_string()),
Event::Newline,
Event::Field(Field {
kind: FieldKind::Radio { pre_checked: false },
name: "color".to_string(),
value: "Green".to_string(),
}),
Event::Text(" green".to_string()),
Event::Newline,
Event::Field(Field {
kind: FieldKind::Radio { pre_checked: true },
name: "color".to_string(),
value: "Blue".to_string(),
}),
Event::Text(" blue".to_string()),
Event::Newline,
];
assert_eq!(expected, events);
}
#[test]
fn can_eventify_cursed_fancy_radio() {
let mu = include_str!("../tests/cases/cursed/fancy_radio.mu");
let lex = Token::lexer(mu);
let events = token_to_event(lex).collect::<Vec<_>>();
let expected = vec![
Event::BackgroundColorSet("900".to_string()),
Event::Field(Field {
kind: FieldKind::Radio { pre_checked: false },
name: "color".to_string(),
value: "Red".to_string(),
}),
Event::BackgroundColorUnset,
Event::Text(" red".to_string()),
Event::Newline,
Event::Newline,
Event::BackgroundColorSet("090".to_string()),
Event::Field(Field {
kind: FieldKind::Radio { pre_checked: false },
name: "color".to_string(),
value: "Green".to_string(),
}),
Event::BackgroundColorUnset,
Event::Text(" green".to_string()),
Event::Newline,
Event::Newline,
Event::BackgroundColorSet("009".to_string()),
Event::Field(Field {
kind: FieldKind::Radio { pre_checked: false },
name: "color".to_string(),
value: "Blue".to_string(),
}),
Event::BackgroundColorUnset,
Event::Text(" blue".to_string()),
Event::Newline,
];
assert_eq!(expected, events);
}
#[test]
fn can_eventify_links() {
let mu = include_str!("../tests/cases/link.mu");
let lex = Token::lexer(mu);
let events = token_to_event(lex).collect::<Vec<_>>();
let expected = vec![
Event::Text("Unlabeled link ".to_string()),
Event::Link(Link {
label: None,
url: "72914442a3689add83a09a767963f57c:/page/index.mu".to_string(),
fields: vec![],
}),
Event::Text(" here.".to_string()),
Event::Newline,
Event::Text("Labeled link ".to_string()),
Event::Link(Link {
label: Some("link label".to_string()),
url: "72914442a3689add83a09a767963f57c:/page/index.mu".to_string(),
fields: vec![],
}),
Event::Newline,
Event::Link(Link {
label: Some("Submit all Fields".to_string()),
url: ":/page/fields.mu".to_string(),
fields: vec!["*".to_string()],
}),
Event::Newline,
Event::Link(Link {
label: Some("Submit some Fields".to_string()),
url: ":/page/fields.mu".to_string(),
fields: vec!["username".to_string(), "auth_token".to_string()],
}),
Event::Newline,
Event::Link(Link {
label: Some("Query the System".to_string()),
url: ":/page/fields.mu".to_string(),
fields: vec![
"username".to_string(),
"auth_token".to_string(),
"action=view".to_string(),
"amount=64".to_string(),
],
}),
Event::Newline,
];
assert_eq!(expected, events);
}
}