1use nom::{
4 branch::alt,
5 bytes::complete::{tag, tag_no_case, take_until, take_while, take_while1},
6 character::complete::{char, digit1, space0, space1},
7 combinator::{map, opt, value},
8 multi::separated_list1,
9 sequence::{delimited, pair, preceded},
10 IResult, Parser,
11};
12
13use crate::ast::*;
14
15#[derive(Debug, Clone, thiserror::Error)]
17pub enum ParseError {
18 #[error("Parse error at line {line}: {message}")]
19 SyntaxError { line: usize, message: String },
20}
21
22pub fn parse(input: &str) -> Result<Diagram, ParseError> {
24 let mut items = Vec::new();
25 let mut title = None;
26 let lines: Vec<&str> = input.lines().collect();
27 let mut i = 0;
28
29 while i < lines.len() {
30 let line = lines[i];
31 let trimmed = line.trim();
32
33 if trimmed.is_empty() {
35 i += 1;
36 continue;
37 }
38
39 if trimmed.starts_with('#') {
41 i += 1;
42 continue;
43 }
44
45 if line.starts_with(' ') && !trimmed.is_empty() && !line.starts_with(" ") {
47 items.push(Item::Description {
49 text: trimmed.to_string(),
50 });
51 i += 1;
52 continue;
53 }
54
55 if let Ok((_, t)) = parse_title(trimmed) {
57 title = Some(t);
58 i += 1;
59 continue;
60 }
61
62 if let Some((position, participants)) = parse_multiline_note_start(trimmed) {
64 let mut note_lines = Vec::new();
65 i += 1;
66 while i < lines.len() {
67 let note_line = lines[i].trim();
68 if note_line.eq_ignore_ascii_case("end note") {
69 break;
70 }
71 note_lines.push(note_line);
72 i += 1;
73 }
74 let text = note_lines.join("\\n");
75 items.push(Item::Note {
76 position,
77 participants,
78 text,
79 });
80 i += 1;
81 continue;
82 }
83
84 if let Some(ref_start) = parse_multiline_ref_start(trimmed) {
87 let mut ref_lines = Vec::new();
88 let mut output_to: Option<String> = None;
89 let mut output_label: Option<String> = None;
90 i += 1;
91 while i < lines.len() {
92 let ref_line = lines[i].trim();
93 if let Some((out_to, out_label)) = parse_ref_end(ref_line) {
95 output_to = out_to;
96 output_label = out_label;
97 break;
98 }
99 ref_lines.push(ref_line);
100 i += 1;
101 }
102 let text = ref_lines.join("\\n");
103 items.push(Item::Ref {
104 participants: ref_start.participants,
105 text,
106 input_from: ref_start.input_from,
107 input_label: ref_start.input_label,
108 output_to,
109 output_label,
110 });
111 i += 1;
112 continue;
113 }
114
115 if let Some((kind, remaining)) = parse_brace_block_start(trimmed) {
117 let mut block_items = Vec::new();
118 let mut brace_depth = 1;
119
120 let after_brace = remaining.trim();
122 if !after_brace.is_empty() && after_brace != "{" {
123 }
125
126 i += 1;
127 while i < lines.len() && brace_depth > 0 {
128 let block_line = lines[i].trim();
129
130 if block_line == "}" {
131 brace_depth -= 1;
132 if brace_depth == 0 {
133 break;
134 }
135 i += 1;
136 continue;
137 }
138
139 if !block_line.is_empty() && !block_line.starts_with('#') {
140 if let Some((nested_kind, _)) = parse_brace_block_start(block_line) {
142 let mut nested_items = Vec::new();
144 let mut nested_depth = 1;
145 i += 1;
146
147 while i < lines.len() && nested_depth > 0 {
148 let nested_line = lines[i].trim();
149 if nested_line == "}" {
150 nested_depth -= 1;
151 if nested_depth == 0 {
152 break;
153 }
154 } else if nested_line.ends_with('{') {
155 nested_depth += 1;
156 }
157
158 if nested_depth > 0
159 && !nested_line.is_empty()
160 && !nested_line.starts_with('#')
161 {
162 if let Ok((_, item)) = parse_line(nested_line) {
163 nested_items.push(item);
164 }
165 }
166 i += 1;
167 }
168
169 block_items.push(Item::Block {
170 kind: nested_kind,
171 label: String::new(),
172 items: nested_items,
173 else_sections: vec![],
174 });
175 } else if let Ok((_, item)) = parse_line(block_line) {
176 block_items.push(item);
177 }
178 }
179 i += 1;
180 }
181
182 items.push(Item::Block {
183 kind,
184 label: String::new(),
185 items: block_items,
186 else_sections: vec![],
187 });
188 i += 1;
189 continue;
190 }
191
192 match parse_line(trimmed) {
194 Ok((_, item)) => {
195 items.push(item);
196 }
197 Err(e) => {
198 return Err(ParseError::SyntaxError {
199 line: i + 1,
200 message: format!("Failed to parse: {:?}", e),
201 });
202 }
203 }
204 i += 1;
205 }
206
207 let items = build_blocks(items)?;
209
210 let mut options = DiagramOptions::default();
212 for item in &items {
213 if let Item::DiagramOption { key, value } = item {
214 if key.eq_ignore_ascii_case("footer") {
215 options.footer = match value.to_lowercase().as_str() {
216 "none" => FooterStyle::None,
217 "bar" => FooterStyle::Bar,
218 "box" => FooterStyle::Box,
219 _ => FooterStyle::Box,
220 };
221 }
222 }
223 }
224
225 Ok(Diagram {
226 title,
227 items,
228 options,
229 })
230}
231
232fn parse_multiline_note_start(input: &str) -> Option<(NotePosition, Vec<String>)> {
234 let input_lower = input.to_lowercase();
235
236 if !input_lower.starts_with("note ") || input.contains(':') {
238 return None;
239 }
240
241 let rest = &input[5..].trim();
242
243 let (position, after_pos) = if rest.to_lowercase().starts_with("left of ") {
245 (NotePosition::Left, &rest[8..])
246 } else if rest.to_lowercase().starts_with("right of ") {
247 (NotePosition::Right, &rest[9..])
248 } else if rest.to_lowercase().starts_with("over ") {
249 (NotePosition::Over, &rest[5..])
250 } else {
251 return None;
252 };
253
254 let participants: Vec<String> = after_pos
256 .split(',')
257 .map(|s| s.trim().to_string())
258 .filter(|s| !s.is_empty())
259 .collect();
260
261 if participants.is_empty() {
262 return None;
263 }
264
265 Some((position, participants))
266}
267
268struct RefStartResult {
270 participants: Vec<String>,
271 input_from: Option<String>,
272 input_label: Option<String>,
273}
274
275fn parse_multiline_ref_start(input: &str) -> Option<RefStartResult> {
278 let mut input_from: Option<String> = None;
279 let mut input_label: Option<String> = None;
280 let mut rest_str = input.to_string();
281
282 if let Some(arrow_pos) = input.to_lowercase().find("->") {
284 let after_arrow = input[arrow_pos + 2..].trim_start();
285 if after_arrow.to_lowercase().starts_with("ref over") {
286 input_from = Some(input[..arrow_pos].trim().to_string());
287 rest_str = after_arrow.to_string(); }
289 }
290
291 let rest_lower = rest_str.to_lowercase();
292
293 if !rest_lower.starts_with("ref over ") && !rest_lower.starts_with("ref over") {
295 return None;
296 }
297
298 let after_ref_over = if rest_lower.starts_with("ref over ") {
300 &rest_str[9..]
301 } else {
302 &rest_str[8..]
303 };
304 let after_ref_over = after_ref_over.trim();
305
306 let (participants_str, label) = if let Some(colon_pos) = after_ref_over.find(':') {
308 let parts = after_ref_over.split_at(colon_pos);
309 (parts.0.trim(), Some(parts.1[1..].trim()))
310 } else {
311 (after_ref_over, None)
312 };
313
314 let participants: Vec<String> = participants_str
316 .split(',')
317 .map(|s| s.trim().to_string())
318 .filter(|s| !s.is_empty())
319 .collect();
320
321 if participants.is_empty() {
322 return None;
323 }
324
325 if input_from.is_some() && label.is_some() {
327 input_label = label.map(|s| s.to_string());
328 }
329
330 if label.is_some() && input_from.is_none() {
333 return None;
335 }
336
337 Some(RefStartResult {
338 participants,
339 input_from,
340 input_label,
341 })
342}
343
344fn parse_ref_end(line: &str) -> Option<(Option<String>, Option<String>)> {
347 let trimmed = line.trim();
348 let lower = trimmed.to_lowercase();
349
350 if !lower.starts_with("end ref") {
351 return None;
352 }
353
354 let rest = &trimmed[7..]; if let Some(arrow_pos) = rest.find("-->") {
358 let after_arrow = &rest[arrow_pos + 3..];
359 if let Some(colon_pos) = after_arrow.find(':') {
361 let to = after_arrow[..colon_pos].trim().to_string();
362 let label = after_arrow[colon_pos + 1..].trim().to_string();
363 return Some((Some(to), Some(label)));
364 } else {
365 let to = after_arrow.trim().to_string();
366 return Some((Some(to), None));
367 }
368 }
369
370 Some((None, None))
372}
373
374fn parse_brace_block_start(input: &str) -> Option<(BlockKind, &str)> {
376 let trimmed = input.trim();
377
378 if let Some(rest) = trimmed.strip_prefix("parallel") {
380 let rest = rest.trim();
381 if rest.starts_with('{') {
382 return Some((BlockKind::Parallel, &rest[1..]));
383 }
384 }
385
386 if let Some(rest) = trimmed.strip_prefix("serial") {
388 let rest = rest.trim();
389 if rest.starts_with('{') {
390 return Some((BlockKind::Serial, &rest[1..]));
391 }
392 }
393
394 None
395}
396
397fn parse_line(input: &str) -> IResult<&str, Item> {
399 alt((
400 parse_state,
401 parse_ref_single_line,
402 parse_option,
403 parse_participant_decl,
404 parse_note,
405 parse_activate,
406 parse_deactivate,
407 parse_destroy,
408 parse_autonumber,
409 parse_block_keyword,
410 parse_message,
411 ))
412 .parse(input)
413}
414
415fn parse_title(input: &str) -> IResult<&str, String> {
417 let (input, _) = tag_no_case("title").parse(input)?;
418 let (input, _) = space1.parse(input)?;
419 let title = input.trim().to_string();
420 Ok(("", title))
421}
422
423fn parse_participant_decl(input: &str) -> IResult<&str, Item> {
425 let (input, kind) = alt((
426 value(ParticipantKind::Participant, tag_no_case("participant")),
427 value(ParticipantKind::Actor, tag_no_case("actor")),
428 ))
429 .parse(input)?;
430
431 let (input, _) = space1.parse(input)?;
432
433 let (input, name) = parse_name(input)?;
435
436 let (input, alias) = opt(preceded(
438 (space1, tag_no_case("as"), space1),
439 parse_identifier,
440 ))
441 .parse(input)?;
442
443 Ok((
444 input,
445 Item::ParticipantDecl {
446 name: name.to_string(),
447 alias: alias.map(|s| s.to_string()),
448 kind,
449 },
450 ))
451}
452
453fn parse_name(input: &str) -> IResult<&str, &str> {
455 alt((
456 tag("["),
458 tag("]"),
459 delimited(char('"'), take_until("\""), char('"')),
461 parse_identifier,
463 ))
464 .parse(input)
465}
466
467fn parse_identifier(input: &str) -> IResult<&str, &str> {
469 take_while1(|c: char| c.is_alphanumeric() || c == '_').parse(input)
470}
471
472fn parse_message(input: &str) -> IResult<&str, Item> {
475 let (input, from) = parse_name(input)?;
476 let (input, arrow) = parse_arrow(input)?;
477 let (input, modifiers) = parse_arrow_modifiers(input)?;
478 let (input, to) = parse_name(input)?;
479 let (input, _) = opt(char(':')).parse(input)?;
480 let (input, _) = space0.parse(input)?;
481 let text = input.trim().to_string();
482
483 Ok((
484 "",
485 Item::Message {
486 from: from.to_string(),
487 to: to.to_string(),
488 text,
489 arrow,
490 activate: modifiers.0,
491 deactivate: modifiers.1,
492 create: modifiers.2,
493 },
494 ))
495}
496
497fn parse_arrow(input: &str) -> IResult<&str, Arrow> {
500 alt((
501 value(Arrow::RESPONSE, tag("<-->")),
503 value(Arrow::SYNC, tag("<->")),
505 value(Arrow::RESPONSE_OPEN, tag("-->>")),
507 value(Arrow::RESPONSE, tag("-->")),
509 value(Arrow::SYNC_OPEN, tag("->>")),
511 map(delimited(tag("->("), digit1, char(')')), |n: &str| Arrow {
513 line: LineStyle::Solid,
514 head: ArrowHead::Filled,
515 delay: n.parse().ok(),
516 }),
517 value(Arrow::SYNC, tag("->")),
519 ))
520 .parse(input)
521}
522
523fn parse_arrow_modifiers(input: &str) -> IResult<&str, (bool, bool, bool)> {
525 let (input, mods) = take_while(|c| c == '+' || c == '-' || c == '*').parse(input)?;
526 let activate = mods.contains('+');
527 let deactivate = mods.contains('-');
528 let create = mods.contains('*');
529 Ok((input, (activate, deactivate, create)))
530}
531
532fn parse_note(input: &str) -> IResult<&str, Item> {
534 let (input, _) = tag_no_case("note").parse(input)?;
535 let (input, _) = space1.parse(input)?;
536
537 let (input, position) = alt((
538 value(NotePosition::Left, pair(tag_no_case("left"), space1)),
539 value(NotePosition::Right, pair(tag_no_case("right"), space1)),
540 value(NotePosition::Over, tag_no_case("")),
541 ))
542 .parse(input)?;
543
544 let (input, position) = if position == NotePosition::Over {
545 let (input, _) = tag_no_case("over").parse(input)?;
546 (input, NotePosition::Over)
547 } else {
548 let (input, _) = tag_no_case("of").parse(input)?;
549 (input, position)
550 };
551
552 let (input, _) = space1.parse(input)?;
553
554 let (input, participants) =
556 separated_list1((space0, char(','), space0), parse_name).parse(input)?;
557
558 let (input, _) = opt(char(':')).parse(input)?;
559 let (input, _) = space0.parse(input)?;
560 let text = input.trim().to_string();
561
562 Ok((
563 "",
564 Item::Note {
565 position,
566 participants: participants.into_iter().map(|s| s.to_string()).collect(),
567 text,
568 },
569 ))
570}
571
572fn parse_state(input: &str) -> IResult<&str, Item> {
574 let (input, _) = tag_no_case("state").parse(input)?;
575 let (input, _) = space1.parse(input)?;
576 let (input, _) = tag_no_case("over").parse(input)?;
577 let (input, _) = space1.parse(input)?;
578
579 let (input, participants) =
581 separated_list1((space0, char(','), space0), parse_name).parse(input)?;
582
583 let (input, _) = opt(char(':')).parse(input)?;
584 let (input, _) = space0.parse(input)?;
585 let text = input.trim().to_string();
586
587 Ok((
588 "",
589 Item::State {
590 participants: participants.into_iter().map(|s| s.to_string()).collect(),
591 text,
592 },
593 ))
594}
595
596fn parse_ref_single_line(input: &str) -> IResult<&str, Item> {
598 let (input, _) = tag_no_case("ref").parse(input)?;
599 let (input, _) = space1.parse(input)?;
600 let (input, _) = tag_no_case("over").parse(input)?;
601 let (input, _) = space1.parse(input)?;
602
603 let (input, participants) =
605 separated_list1((space0, char(','), space0), parse_name).parse(input)?;
606
607 let (input, _) = char(':').parse(input)?;
608 let (input, _) = space0.parse(input)?;
609 let text = input.trim().to_string();
610
611 Ok((
612 "",
613 Item::Ref {
614 participants: participants.into_iter().map(|s| s.to_string()).collect(),
615 text,
616 input_from: None,
617 input_label: None,
618 output_to: None,
619 output_label: None,
620 },
621 ))
622}
623
624fn parse_option(input: &str) -> IResult<&str, Item> {
626 let (input, _) = tag_no_case("option").parse(input)?;
627 let (input, _) = space1.parse(input)?;
628 let (input, key) = take_while1(|c: char| c.is_alphanumeric() || c == '_').parse(input)?;
629 let (input, _) = char('=').parse(input)?;
630 let (_input, value) = take_while1(|c: char| !c.is_whitespace()).parse(input)?;
631
632 Ok((
633 "",
634 Item::DiagramOption {
635 key: key.to_string(),
636 value: value.to_string(),
637 },
638 ))
639}
640
641fn parse_activate(input: &str) -> IResult<&str, Item> {
643 let (input, _) = tag_no_case("activate").parse(input)?;
644 let (input, _) = space1.parse(input)?;
645 let (_input, participant) = parse_name(input)?;
646 Ok((
647 "",
648 Item::Activate {
649 participant: participant.to_string(),
650 },
651 ))
652}
653
654fn parse_deactivate(input: &str) -> IResult<&str, Item> {
656 let (input, _) = tag_no_case("deactivate").parse(input)?;
657 let (input, _) = space1.parse(input)?;
658 let (_input, participant) = parse_name(input)?;
659 Ok((
660 "",
661 Item::Deactivate {
662 participant: participant.to_string(),
663 },
664 ))
665}
666
667fn parse_destroy(input: &str) -> IResult<&str, Item> {
669 let (input, _) = tag_no_case("destroy").parse(input)?;
670 let (input, _) = space1.parse(input)?;
671 let (_input, participant) = parse_name(input)?;
672 Ok((
673 "",
674 Item::Destroy {
675 participant: participant.to_string(),
676 },
677 ))
678}
679
680fn parse_autonumber(input: &str) -> IResult<&str, Item> {
682 let (input, _) = tag_no_case("autonumber").parse(input)?;
683
684 let (_input, rest) =
685 opt(preceded(space1, take_while1(|c: char| !c.is_whitespace()))).parse(input)?;
686
687 let (enabled, start) = match rest {
688 Some("off") => (false, None),
689 Some(n) => (true, n.parse().ok()),
690 None => (true, None),
691 };
692
693 Ok(("", Item::Autonumber { enabled, start }))
694}
695
696fn parse_block_keyword(input: &str) -> IResult<&str, Item> {
698 alt((parse_block_start, parse_else, parse_end)).parse(input)
699}
700
701fn parse_block_start(input: &str) -> IResult<&str, Item> {
703 let (input, kind) = alt((
704 value(BlockKind::Alt, tag_no_case("alt")),
705 value(BlockKind::Opt, tag_no_case("opt")),
706 value(BlockKind::Loop, tag_no_case("loop")),
707 value(BlockKind::Par, tag_no_case("par")),
708 value(BlockKind::Seq, tag_no_case("seq")),
709 ))
710 .parse(input)?;
711
712 let (input, _) = space0.parse(input)?;
713 let label = input.trim().to_string();
714
715 Ok((
717 "",
718 Item::Block {
719 kind,
720 label,
721 items: vec![],
722 else_sections: vec![],
723 },
724 ))
725}
726
727fn parse_else(input: &str) -> IResult<&str, Item> {
729 let (input, _) = tag_no_case("else").parse(input)?;
730 let (input, _) = space0.parse(input)?;
731 let label = input.trim().to_string();
732
733 Ok((
735 "",
736 Item::Block {
737 kind: BlockKind::Alt, label: format!("__ELSE__{}", label),
739 items: vec![],
740 else_sections: vec![],
741 },
742 ))
743}
744
745fn parse_end(input: &str) -> IResult<&str, Item> {
747 let trimmed = input.trim().to_lowercase();
748 if trimmed.starts_with("end note") || trimmed.starts_with("end ref") {
750 return Err(nom::Err::Error(nom::error::Error::new(
751 input,
752 nom::error::ErrorKind::Tag,
753 )));
754 }
755 let (_input, _) = tag_no_case("end").parse(input)?;
756 Ok((
757 "",
758 Item::Block {
759 kind: BlockKind::Alt, label: "__END__".to_string(),
761 items: vec![],
762 else_sections: vec![],
763 },
764 ))
765}
766
767fn build_blocks(items: Vec<Item>) -> Result<Vec<Item>, ParseError> {
769 use crate::ast::ElseSection;
770
771 let mut result = Vec::new();
772 struct StackEntry {
774 kind: BlockKind,
775 label: String,
776 items: Vec<Item>,
777 else_sections: Vec<ElseSection>,
778 current_else_items: Vec<Item>,
779 current_else_label: Option<String>,
780 in_else_branch: bool,
781 }
782 let mut stack: Vec<StackEntry> = Vec::new();
783
784 for item in items {
785 match &item {
786 Item::Block { label, .. } if label == "__END__" => {
787 if let Some(mut entry) = stack.pop() {
789 if entry.in_else_branch && !entry.current_else_items.is_empty() {
791 entry.else_sections.push(ElseSection {
792 label: entry.current_else_label.take(),
793 items: std::mem::take(&mut entry.current_else_items),
794 });
795 }
796 let block = Item::Block {
797 kind: entry.kind,
798 label: entry.label,
799 items: entry.items,
800 else_sections: entry.else_sections,
801 };
802 if let Some(parent) = stack.last_mut() {
803 if parent.in_else_branch {
804 parent.current_else_items.push(block);
805 } else {
806 parent.items.push(block);
807 }
808 } else {
809 result.push(block);
810 }
811 }
812 }
813 Item::Block { label, .. } if label.starts_with("__ELSE__") => {
814 let else_label_text = label.strip_prefix("__ELSE__").unwrap_or("").to_string();
816 if let Some(entry) = stack.last_mut() {
817 if entry.in_else_branch && !entry.current_else_items.is_empty() {
819 entry.else_sections.push(ElseSection {
820 label: entry.current_else_label.take(),
821 items: std::mem::take(&mut entry.current_else_items),
822 });
823 }
824 entry.in_else_branch = true;
826 entry.current_else_items = Vec::new();
827 entry.current_else_label = if else_label_text.is_empty() {
828 None
829 } else {
830 Some(else_label_text)
831 };
832 }
833 }
834 Item::Block {
835 kind,
836 label,
837 items,
838 else_sections,
839 ..
840 } if !label.starts_with("__") => {
841 if matches!(kind, BlockKind::Parallel | BlockKind::Serial) || !items.is_empty() {
843 let block = Item::Block {
845 kind: *kind,
846 label: label.clone(),
847 items: items.clone(),
848 else_sections: else_sections.clone(),
849 };
850 if let Some(parent) = stack.last_mut() {
851 if parent.in_else_branch {
852 parent.current_else_items.push(block);
853 } else {
854 parent.items.push(block);
855 }
856 } else {
857 result.push(block);
858 }
859 } else {
860 stack.push(StackEntry {
862 kind: *kind,
863 label: label.clone(),
864 items: Vec::new(),
865 else_sections: Vec::new(),
866 current_else_items: Vec::new(),
867 current_else_label: None,
868 in_else_branch: false,
869 });
870 }
871 }
872 _ => {
873 if let Some(parent) = stack.last_mut() {
875 if parent.in_else_branch {
876 parent.current_else_items.push(item);
877 } else {
878 parent.items.push(item);
879 }
880 } else {
881 result.push(item);
882 }
883 }
884 }
885 }
886
887 Ok(result)
888}
889
890#[cfg(test)]
891mod tests {
892 use super::*;
893
894 #[test]
895 fn test_simple_message() {
896 let result = parse("Alice->Bob: Hello").unwrap();
897 assert_eq!(result.items.len(), 1);
898 match &result.items[0] {
899 Item::Message { from, to, text, .. } => {
900 assert_eq!(from, "Alice");
901 assert_eq!(to, "Bob");
902 assert_eq!(text, "Hello");
903 }
904 _ => panic!("Expected Message"),
905 }
906 }
907
908 #[test]
909 fn test_participant_decl() {
910 let result = parse("participant Alice\nactor Bob").unwrap();
911 assert_eq!(result.items.len(), 2);
912 }
913
914 #[test]
915 fn test_note() {
916 let result = parse("note over Alice: Hello").unwrap();
917 assert_eq!(result.items.len(), 1);
918 match &result.items[0] {
919 Item::Note {
920 position,
921 participants,
922 text,
923 } => {
924 assert_eq!(*position, NotePosition::Over);
925 assert_eq!(participants, &["Alice"]);
926 assert_eq!(text, "Hello");
927 }
928 _ => panic!("Expected Note"),
929 }
930 }
931
932 #[test]
933 fn test_opt_block() {
934 let result = parse("opt condition\nAlice->Bob: Hello\nend").unwrap();
935 assert_eq!(result.items.len(), 1);
936 match &result.items[0] {
937 Item::Block {
938 kind, label, items, ..
939 } => {
940 assert_eq!(*kind, BlockKind::Opt);
941 assert_eq!(label, "condition");
942 assert_eq!(items.len(), 1);
943 }
944 _ => panic!("Expected Block"),
945 }
946 }
947
948 #[test]
949 fn test_alt_else_block() {
950 let result =
951 parse("alt success\nAlice->Bob: OK\nelse failure\nAlice->Bob: Error\nend").unwrap();
952 assert_eq!(result.items.len(), 1);
953 match &result.items[0] {
954 Item::Block {
955 kind,
956 label,
957 items,
958 else_sections,
959 ..
960 } => {
961 assert_eq!(*kind, BlockKind::Alt);
962 assert_eq!(label, "success");
963 assert_eq!(items.len(), 1);
964 assert_eq!(else_sections.len(), 1);
965 assert_eq!(else_sections[0].items.len(), 1);
966 }
967 _ => panic!("Expected Block"),
968 }
969 }
970
971 #[test]
973 fn test_comment() {
974 let result = parse("# This is a comment\nAlice->Bob: Hello").unwrap();
975 assert_eq!(result.items.len(), 1);
976 match &result.items[0] {
977 Item::Message { from, to, text, .. } => {
978 assert_eq!(from, "Alice");
979 assert_eq!(to, "Bob");
980 assert_eq!(text, "Hello");
981 }
982 _ => panic!("Expected Message"),
983 }
984 }
985
986 #[test]
988 fn test_multiline_note() {
989 let input = r#"note left of Alice
990Line 1
991Line 2
992end note"#;
993 let result = parse(input).unwrap();
994 assert_eq!(result.items.len(), 1);
995 match &result.items[0] {
996 Item::Note {
997 position,
998 participants,
999 text,
1000 } => {
1001 assert_eq!(*position, NotePosition::Left);
1002 assert_eq!(participants, &["Alice"]);
1003 assert_eq!(text, "Line 1\\nLine 2");
1004 }
1005 _ => panic!("Expected Note"),
1006 }
1007 }
1008
1009 #[test]
1011 fn test_state() {
1012 let result = parse("state over Server: LISTEN").unwrap();
1013 assert_eq!(result.items.len(), 1);
1014 match &result.items[0] {
1015 Item::State { participants, text } => {
1016 assert_eq!(participants, &["Server"]);
1017 assert_eq!(text, "LISTEN");
1018 }
1019 _ => panic!("Expected State"),
1020 }
1021 }
1022
1023 #[test]
1025 fn test_ref() {
1026 let result = parse("ref over Alice, Bob: See other diagram").unwrap();
1027 assert_eq!(result.items.len(), 1);
1028 match &result.items[0] {
1029 Item::Ref {
1030 participants, text, ..
1031 } => {
1032 assert_eq!(participants, &["Alice", "Bob"]);
1033 assert_eq!(text, "See other diagram");
1034 }
1035 _ => panic!("Expected Ref"),
1036 }
1037 }
1038
1039 #[test]
1040 fn test_ref_input_signal_multiline() {
1041 let input = r#"Alice->ref over Bob, Carol: Input signal
1042line 1
1043line 2
1044end ref-->Alice: Output signal"#;
1045 let result = parse(input).unwrap();
1046 assert_eq!(result.items.len(), 1);
1047 match &result.items[0] {
1048 Item::Ref {
1049 participants,
1050 text,
1051 input_from,
1052 input_label,
1053 output_to,
1054 output_label,
1055 } => {
1056 assert_eq!(participants, &["Bob", "Carol"]);
1057 assert_eq!(text, "line 1\\nline 2");
1058 assert_eq!(input_from.as_deref(), Some("Alice"));
1059 assert_eq!(input_label.as_deref(), Some("Input signal"));
1060 assert_eq!(output_to.as_deref(), Some("Alice"));
1061 assert_eq!(output_label.as_deref(), Some("Output signal"));
1062 }
1063 _ => panic!("Expected Ref"),
1064 }
1065 }
1066
1067 #[test]
1069 fn test_option() {
1070 let result = parse("option footer=none").unwrap();
1071 assert_eq!(result.items.len(), 1);
1072 match &result.items[0] {
1073 Item::DiagramOption { key, value } => {
1074 assert_eq!(key, "footer");
1075 assert_eq!(value, "none");
1076 }
1077 _ => panic!("Expected DiagramOption"),
1078 }
1079 }
1080
1081 #[test]
1083 fn test_quoted_name_with_colon() {
1084 let result = parse(r#"":Alice"->":Bob": Hello"#).unwrap();
1085 assert_eq!(result.items.len(), 1);
1086 match &result.items[0] {
1087 Item::Message { from, to, text, .. } => {
1088 assert_eq!(from, ":Alice");
1089 assert_eq!(to, ":Bob");
1090 assert_eq!(text, "Hello");
1091 }
1092 _ => panic!("Expected Message"),
1093 }
1094 }
1095}