use winnow::{
Parser,
ascii::{multispace0, multispace1},
combinator::{alt, opt, peek},
error::InputError,
token::{one_of, take_until, take_while},
};
use crate::ast::ParticipantKind;
pub fn keyword<'i>(kw: &'static str) -> impl Parser<&'i str, &'i str, InputError<&'i str>> {
move |input: &mut &'i str| {
let lower = kw.to_ascii_lowercase();
if let Some(candidate) = input.get(..lower.len())
&& candidate.to_ascii_lowercase() == lower
{
let after = input[lower.len()..].chars().next();
if after
.is_none_or(|c| c.is_whitespace() || c == ':' || c == '\n' || c == '\r' || c == '{')
{
let matched = &input[..lower.len()];
*input = &input[lower.len()..];
return Ok(matched);
}
}
Err(InputError::at(*input))
}
}
pub fn participant_kind<'i>(input: &mut &'i str) -> PResult<'i, ParticipantKind> {
use ParticipantKind::*;
alt((
keyword("actor").map(|_| Actor),
keyword("boundary").map(|_| Boundary),
keyword("control").map(|_| Control),
keyword("entity").map(|_| Entity),
keyword("database").map(|_| Database),
keyword("collections").map(|_| Collections),
keyword("queue").map(|_| Queue),
))
.parse_next(input)
}
pub fn rest_of_line<'i>(input: &mut &'i str) -> PResult<'i, String> {
take_while(1.., |c: char| c != '\n' && c != '\r')
.map(|s: &str| s.trim().to_string())
.parse_next(input)
}
pub type PResult<'i, O> = Result<O, InputError<&'i str>>;
pub fn ws<'i>(input: &mut &'i str) -> PResult<'i, &'i str> {
multispace0.parse_next(input)
}
pub fn inline_ws<'i>(input: &mut &'i str) -> PResult<'i, &'i str> {
take_while(0.., |c: char| c == ' ' || c == '\t').parse_next(input)
}
pub fn ws1<'i>(input: &mut &'i str) -> PResult<'i, &'i str> {
multispace1.parse_next(input)
}
pub fn inline_ws_and_comments<'i>(input: &mut &'i str) -> PResult<'i, ()> {
loop {
let before = input.len();
inline_ws(input)?;
if input.starts_with("%%") {
let _ = take_while(0.., |c: char| c != '\n' && c != '\r').parse_next(input)?;
}
if input.len() == before {
break;
}
}
Ok(())
}
pub fn line_comment<'i>(input: &mut &'i str) -> PResult<'i, ()> {
let _ = "%%".parse_next(input)?;
let _ = take_until(1.., '\n').parse_next(input)?;
let _ = opt('\n').parse_next(input)?;
Ok(())
}
pub fn skip_ws_and_comments<'i>(input: &mut &'i str) -> PResult<'i, ()> {
loop {
let mut advanced = false;
if ws1(input).is_ok() {
advanced = true;
}
if input.starts_with('\n') || input.starts_with("\r\n") {
if input.starts_with("\r\n") {
*input = &input[2..];
} else {
*input = &input[1..];
}
advanced = true;
}
if line_comment(input).is_ok() {
advanced = true;
}
if !advanced {
break;
}
}
Ok(())
}
pub fn has_input(input: &mut &str) -> bool {
!input.is_empty()
}
pub fn skip_line<'i>(input: &mut &'i str) -> PResult<'i, ()> {
if input.is_empty() {
return Ok(());
}
let before = input.len();
let _ = take_while(0.., |c: char| c != '\n' && c != '\r').parse_next(input)?;
let _ = opt(("\r\n", "\n")).parse_next(input)?;
if input.len() == before {
let _ = take_while(1.., |_c: char| true).parse_next(input)?;
}
Ok(())
}
pub fn attempt<'i, O>(
mut parser: impl Parser<&'i str, O, InputError<&'i str>>,
input: &mut &'i str,
) -> Option<O> {
let start = *input;
match parser.parse_next(input) {
Ok(value) => Some(value),
Err(_) => {
*input = start;
None
}
}
}
pub fn consume_line<'i>(input: &mut &'i str) -> PResult<'i, ()> {
let _ = take_while(0.., |c: char| c != '\n' && c != '\r').parse_next(input)?;
let _ = opt(alt(("\r\n", "\n"))).parse_next(input)?;
Ok(())
}
pub fn peek_end<'i>(input: &mut &'i str) -> PResult<'i, &'i str> {
peek("end").parse_next(input)
}
pub fn identifier<'i>(input: &mut &'i str) -> PResult<'i, String> {
let s = *input;
let mut end = 0usize;
let mut chars = s.char_indices().peekable();
let mut first = true;
while let Some((i, c)) = chars.next() {
if first {
if !(c.is_alphabetic() || c == '_') {
break;
}
first = false;
end = i + c.len_utf8();
continue;
}
if c.is_alphanumeric() || c == '_' {
end = i + c.len_utf8();
continue;
}
if c == '-' {
match chars.peek() {
Some((_, '-' | '.' | '>')) => break,
_ => {
end = i + c.len_utf8();
continue;
}
}
}
break;
}
if end == 0 {
return Err(InputError::at(*input));
}
*input = &s[end..];
Ok(s[..end].to_string())
}
pub fn quoted_string<'i>(input: &mut &'i str) -> PResult<'i, String> {
let q = one_of(['"', '\'']).parse_next(input)?;
let content = take_until(1.., q).parse_next(input)?;
let _ = one_of([q]).parse_next(input)?;
Ok(content.to_string())
}
fn strip_wrapping_quotes(s: &str) -> String {
let t = s.trim();
let Some(first) = t.chars().next() else {
return String::new();
};
if first != '"' && first != '\'' {
return t.to_string();
}
let mut escaped = false;
let mut close = None;
for (i, c) in t.char_indices().skip(1) {
if escaped {
escaped = false;
} else if c == '\\' {
escaped = true;
} else if c == first {
close = Some(i);
break;
}
}
match close {
Some(i) if i + first.len_utf8() == t.len() => t[first.len_utf8()..i].to_string(),
_ => t.to_string(),
}
}
fn label_until<'i>(close: &'static str) -> impl Parser<&'i str, String, InputError<&'i str>> {
move |input: &mut &'i str| {
let s = *input;
let mut quote: Option<char> = None;
let mut escaped = false;
let mut seen_content = false;
let mut end = None;
for (i, c) in s.char_indices() {
if escaped {
escaped = false;
continue;
}
if let Some(q) = quote {
if c == '\\' {
escaped = true;
} else if c == q {
quote = None;
}
continue;
}
match c {
'"' | '\'' if !seen_content => {
quote = Some(c);
seen_content = true;
}
'\n' | '\r' => break,
_ if s[i..].starts_with(close) => {
end = Some(i);
break;
}
_ => {
if !c.is_whitespace() {
seen_content = true;
}
}
}
}
let idx = end.ok_or_else(|| InputError::at(s))?;
let content = strip_wrapping_quotes(&s[..idx]);
*input = &s[idx..];
Ok(content)
}
}
pub fn shape_label<'i>(
open: &'static str,
close: &'static str,
) -> impl Parser<&'i str, String, InputError<&'i str>> {
move |input: &mut &'i str| {
let mut open = open;
open.parse_next(input)?;
let content = label_until(close).parse_next(input)?;
let mut close = close;
close.parse_next(input)?;
Ok(content)
}
}
const BARE_LABEL_STOPS: &[&str] = &[
"-->", "---", "--o", "--x", "-.->", ".->", "==>", "~~~", "--|",
];
pub fn bare_label<'i>(input: &mut &'i str) -> PResult<'i, String> {
let s = *input;
let mut rest = s.chars();
match (rest.next(), rest.next()) {
(Some('>'), _) | (Some('|'), _) => return Err(InputError::at(s)),
(Some('o' | 'x'), None) => return Err(InputError::at(s)),
(Some('o' | 'x'), Some(c)) if c.is_whitespace() => return Err(InputError::at(s)),
(Some('-'), Some('-' | '.' | '>')) => return Err(InputError::at(s)),
(Some('='), Some('=' | '>')) => return Err(InputError::at(s)),
_ => {}
}
let mut end = 0usize;
let mut quote: Option<char> = None;
let mut escaped = false;
let mut seen_content = false;
for (i, c) in s.char_indices() {
if escaped {
escaped = false;
seen_content = true;
end = i + c.len_utf8();
continue;
}
if let Some(q) = quote {
if c == '\\' {
escaped = true;
} else if c == q {
quote = None;
}
end = i + c.len_utf8();
continue;
}
match c {
'"' | '\'' if !seen_content => {
quote = Some(c);
seen_content = true;
end = i + c.len_utf8();
}
'\n' | '\r' | ';' => break,
_ if BARE_LABEL_STOPS.iter().any(|t| s[i..].starts_with(t)) => break,
_ => {
if !c.is_whitespace() {
seen_content = true;
}
end = i + c.len_utf8();
}
}
}
let content = strip_wrapping_quotes(&s[..end]);
if content.is_empty() {
return Err(InputError::at(s));
}
*input = &s[end..];
Ok(content)
}
pub fn direction<'i>(input: &mut &'i str) -> PResult<'i, crate::ast::Direction> {
use crate::ast::Direction;
alt((
"TB".map(|_| Direction::TB),
"TD".map(|_| Direction::TD),
"BT".map(|_| Direction::BT),
"RL".map(|_| Direction::RL),
"LR".map(|_| Direction::LR),
))
.parse_next(input)
}