osd_core/
parser.rs

1//! Parser for WebSequenceDiagrams-compatible sequence diagram syntax
2
3use 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/// Parse error
16#[derive(Debug, Clone, thiserror::Error)]
17pub enum ParseError {
18    #[error("Parse error at line {line}: {message}")]
19    SyntaxError { line: usize, message: String },
20}
21
22/// Parse a complete diagram
23pub 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        // Skip empty lines
34        if trimmed.is_empty() {
35            i += 1;
36            continue;
37        }
38
39        // Task 5: Skip comment lines (# ...)
40        if trimmed.starts_with('#') {
41            i += 1;
42            continue;
43        }
44
45        // Task 7: Extended text description (lines starting with space but not empty)
46        if line.starts_with(' ') && !trimmed.is_empty() && !line.starts_with("  ") {
47            // Single space indent is description
48            items.push(Item::Description {
49                text: trimmed.to_string(),
50            });
51            i += 1;
52            continue;
53        }
54
55        // Try parsing title first
56        if let Ok((_, t)) = parse_title(trimmed) {
57            title = Some(t);
58            i += 1;
59            continue;
60        }
61
62        // Task 1: Check for multiline note (note without colon)
63        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        // Task 3: Check for multiline ref (ref over ... without colon on same line ending with text)
85        // Also handles A->ref over B: input ... end ref-->A: output
86        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                // Check for end ref with optional output signal
94                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        // Task 8: Check for parallel { or serial { brace syntax
116        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            // Check if there's content after the opening brace on the same line
121            let after_brace = remaining.trim();
122            if !after_brace.is_empty() && after_brace != "{" {
123                // Parse content after brace if any
124            }
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                    // Recursively parse nested content
141                    if let Some((nested_kind, _)) = parse_brace_block_start(block_line) {
142                        // Handle nested parallel/serial blocks
143                        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        // Regular line parsing
193        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    // Second pass: handle blocks (alt/opt/loop/par/end/else)
208    let items = build_blocks(items)?;
209
210    // Extract options from items
211    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
232/// Check if line starts a multiline note (note without colon)
233fn parse_multiline_note_start(input: &str) -> Option<(NotePosition, Vec<String>)> {
234    let input_lower = input.to_lowercase();
235
236    // Must start with "note" but not have a colon
237    if !input_lower.starts_with("note ") || input.contains(':') {
238        return None;
239    }
240
241    let rest = &input[5..].trim();
242
243    // Determine position
244    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    // Parse participants
255    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
268/// Result of parsing a multiline ref start
269struct RefStartResult {
270    participants: Vec<String>,
271    input_from: Option<String>,
272    input_label: Option<String>,
273}
274
275/// Check if line starts a multiline ref (ref over ... without ending text)
276/// Also handles A->ref over B: label syntax for input signal
277fn 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    // Check for "A->ref over" pattern (input signal)
283    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(); // Keep "ref over ..."
288        }
289    }
290
291    let rest_lower = rest_str.to_lowercase();
292
293    // Must start with "ref over"
294    if !rest_lower.starts_with("ref over ") && !rest_lower.starts_with("ref over") {
295        return None;
296    }
297
298    // Extract part after "ref over "
299    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    // Check for colon (input label for single-line or multiline with label)
307    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    // Parse participants
315    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 there's a label with input_from, this is "A->ref over B: label" format
326    if input_from.is_some() && label.is_some() {
327        input_label = label.map(|s| s.to_string());
328    }
329
330    // For multiline ref, we expect no colon (or the colon case is handled differently)
331    // But if input signal is present with a colon, it's still a valid multiline ref start
332    if label.is_some() && input_from.is_none() {
333        // This is a single-line ref like "ref over A, B: text" - not a multiline start
334        return None;
335    }
336
337    Some(RefStartResult {
338        participants,
339        input_from,
340        input_label,
341    })
342}
343
344/// Parse end ref line with optional output signal
345/// Returns (output_to, output_label)
346fn 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..]; // After "end ref"
355
356    // Check for output signal "-->A: label"
357    if let Some(arrow_pos) = rest.find("-->") {
358        let after_arrow = &rest[arrow_pos + 3..];
359        // Parse "A: label" or just "A"
360        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    // Simple "end ref"
371    Some((None, None))
372}
373
374/// Check if line starts a brace block (parallel { or serial {)
375fn parse_brace_block_start(input: &str) -> Option<(BlockKind, &str)> {
376    let trimmed = input.trim();
377
378    // Check for "parallel {" or "parallel{"
379    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    // Check for "serial {" or "serial{"
387    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
397/// Parse a single line
398fn 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
415/// Parse title
416fn 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
423/// Parse participant declaration: `participant Name` or `actor Name` or `participant "Long Name" as L`
424fn 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    // Parse name (possibly quoted)
434    let (input, name) = parse_name(input)?;
435
436    // Check for alias
437    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
453/// Parse a name (quoted or unquoted) - Task 6: supports colon in quoted names
454fn parse_name(input: &str) -> IResult<&str, &str> {
455    alt((
456        // Quoted name (can contain colons, spaces, etc.)
457        delimited(char('"'), take_until("\""), char('"')),
458        // Unquoted identifier
459        parse_identifier,
460    ))
461    .parse(input)
462}
463
464/// Parse an identifier (alphanumeric + underscore)
465fn parse_identifier(input: &str) -> IResult<&str, &str> {
466    take_while1(|c: char| c.is_alphanumeric() || c == '_').parse(input)
467}
468
469/// Parse a message: `A->B: text` or `A->>B: text` etc.
470/// Task 6: Now supports quoted names with colons
471fn parse_message(input: &str) -> IResult<&str, Item> {
472    let (input, from) = parse_name(input)?;
473    let (input, arrow) = parse_arrow(input)?;
474    let (input, modifiers) = parse_arrow_modifiers(input)?;
475    let (input, to) = parse_name(input)?;
476    let (input, _) = opt(char(':')).parse(input)?;
477    let (input, _) = space0.parse(input)?;
478    let text = input.trim().to_string();
479
480    Ok((
481        "",
482        Item::Message {
483            from: from.to_string(),
484            to: to.to_string(),
485            text,
486            arrow,
487            activate: modifiers.0,
488            deactivate: modifiers.1,
489            create: modifiers.2,
490        },
491    ))
492}
493
494/// Parse arrow: `->`, `->>`, `-->`, `-->>`, `->(n)`, `<->`, `<-->`
495/// Task 9: Added bidirectional arrow support (though WSD may not use it)
496fn parse_arrow(input: &str) -> IResult<&str, Arrow> {
497    alt((
498        // <--> bidirectional dashed (if needed)
499        value(Arrow::RESPONSE, tag("<-->")),
500        // <-> bidirectional solid (if needed)
501        value(Arrow::SYNC, tag("<->")),
502        // -->> dashed open
503        value(Arrow::RESPONSE_OPEN, tag("-->>")),
504        // --> dashed filled
505        value(Arrow::RESPONSE, tag("-->")),
506        // ->> solid open
507        value(Arrow::SYNC_OPEN, tag("->>")),
508        // ->(n) delayed
509        map(delimited(tag("->("), digit1, char(')')), |n: &str| Arrow {
510            line: LineStyle::Solid,
511            head: ArrowHead::Filled,
512            delay: n.parse().ok(),
513        }),
514        // -> solid filled
515        value(Arrow::SYNC, tag("->")),
516    ))
517    .parse(input)
518}
519
520/// Parse arrow modifiers: `+` (activate), `-` (deactivate), `*` (create)
521fn parse_arrow_modifiers(input: &str) -> IResult<&str, (bool, bool, bool)> {
522    let (input, mods) = take_while(|c| c == '+' || c == '-' || c == '*').parse(input)?;
523    let activate = mods.contains('+');
524    let deactivate = mods.contains('-');
525    let create = mods.contains('*');
526    Ok((input, (activate, deactivate, create)))
527}
528
529/// Parse note: `note left of A: text`, `note right of A: text`, `note over A: text`, `note over A,B: text`
530fn parse_note(input: &str) -> IResult<&str, Item> {
531    let (input, _) = tag_no_case("note").parse(input)?;
532    let (input, _) = space1.parse(input)?;
533
534    let (input, position) = alt((
535        value(NotePosition::Left, pair(tag_no_case("left"), space1)),
536        value(NotePosition::Right, pair(tag_no_case("right"), space1)),
537        value(NotePosition::Over, tag_no_case("")),
538    ))
539    .parse(input)?;
540
541    let (input, position) = if position == NotePosition::Over {
542        let (input, _) = tag_no_case("over").parse(input)?;
543        (input, NotePosition::Over)
544    } else {
545        let (input, _) = tag_no_case("of").parse(input)?;
546        (input, position)
547    };
548
549    let (input, _) = space1.parse(input)?;
550
551    // Parse participants (comma-separated) - support quoted names
552    let (input, participants) =
553        separated_list1((space0, char(','), space0), parse_name).parse(input)?;
554
555    let (input, _) = opt(char(':')).parse(input)?;
556    let (input, _) = space0.parse(input)?;
557    let text = input.trim().to_string();
558
559    Ok((
560        "",
561        Item::Note {
562            position,
563            participants: participants.into_iter().map(|s| s.to_string()).collect(),
564            text,
565        },
566    ))
567}
568
569/// Task 2: Parse state: `state over A: text` or `state over A,B: text`
570fn parse_state(input: &str) -> IResult<&str, Item> {
571    let (input, _) = tag_no_case("state").parse(input)?;
572    let (input, _) = space1.parse(input)?;
573    let (input, _) = tag_no_case("over").parse(input)?;
574    let (input, _) = space1.parse(input)?;
575
576    // Parse participants (comma-separated)
577    let (input, participants) =
578        separated_list1((space0, char(','), space0), parse_name).parse(input)?;
579
580    let (input, _) = opt(char(':')).parse(input)?;
581    let (input, _) = space0.parse(input)?;
582    let text = input.trim().to_string();
583
584    Ok((
585        "",
586        Item::State {
587            participants: participants.into_iter().map(|s| s.to_string()).collect(),
588            text,
589        },
590    ))
591}
592
593/// Task 3: Parse single-line ref: `ref over A,B: text`
594fn parse_ref_single_line(input: &str) -> IResult<&str, Item> {
595    let (input, _) = tag_no_case("ref").parse(input)?;
596    let (input, _) = space1.parse(input)?;
597    let (input, _) = tag_no_case("over").parse(input)?;
598    let (input, _) = space1.parse(input)?;
599
600    // Parse participants (comma-separated)
601    let (input, participants) =
602        separated_list1((space0, char(','), space0), parse_name).parse(input)?;
603
604    let (input, _) = char(':').parse(input)?;
605    let (input, _) = space0.parse(input)?;
606    let text = input.trim().to_string();
607
608    Ok((
609        "",
610        Item::Ref {
611            participants: participants.into_iter().map(|s| s.to_string()).collect(),
612            text,
613            input_from: None,
614            input_label: None,
615            output_to: None,
616            output_label: None,
617        },
618    ))
619}
620
621/// Task 4: Parse option: `option key=value`
622fn parse_option(input: &str) -> IResult<&str, Item> {
623    let (input, _) = tag_no_case("option").parse(input)?;
624    let (input, _) = space1.parse(input)?;
625    let (input, key) = take_while1(|c: char| c.is_alphanumeric() || c == '_').parse(input)?;
626    let (input, _) = char('=').parse(input)?;
627    let (_input, value) = take_while1(|c: char| !c.is_whitespace()).parse(input)?;
628
629    Ok((
630        "",
631        Item::DiagramOption {
632            key: key.to_string(),
633            value: value.to_string(),
634        },
635    ))
636}
637
638/// Parse activate: `activate A`
639fn parse_activate(input: &str) -> IResult<&str, Item> {
640    let (input, _) = tag_no_case("activate").parse(input)?;
641    let (input, _) = space1.parse(input)?;
642    let (_input, participant) = parse_name(input)?;
643    Ok((
644        "",
645        Item::Activate {
646            participant: participant.to_string(),
647        },
648    ))
649}
650
651/// Parse deactivate: `deactivate A`
652fn parse_deactivate(input: &str) -> IResult<&str, Item> {
653    let (input, _) = tag_no_case("deactivate").parse(input)?;
654    let (input, _) = space1.parse(input)?;
655    let (_input, participant) = parse_name(input)?;
656    Ok((
657        "",
658        Item::Deactivate {
659            participant: participant.to_string(),
660        },
661    ))
662}
663
664/// Parse destroy: `destroy A`
665fn parse_destroy(input: &str) -> IResult<&str, Item> {
666    let (input, _) = tag_no_case("destroy").parse(input)?;
667    let (input, _) = space1.parse(input)?;
668    let (_input, participant) = parse_name(input)?;
669    Ok((
670        "",
671        Item::Destroy {
672            participant: participant.to_string(),
673        },
674    ))
675}
676
677/// Parse autonumber: `autonumber` or `autonumber off` or `autonumber 5`
678fn parse_autonumber(input: &str) -> IResult<&str, Item> {
679    let (input, _) = tag_no_case("autonumber").parse(input)?;
680
681    let (_input, rest) =
682        opt(preceded(space1, take_while1(|c: char| !c.is_whitespace()))).parse(input)?;
683
684    let (enabled, start) = match rest {
685        Some("off") => (false, None),
686        Some(n) => (true, n.parse().ok()),
687        None => (true, None),
688    };
689
690    Ok(("", Item::Autonumber { enabled, start }))
691}
692
693/// Parse block keywords: alt, opt, loop, par, else, end
694fn parse_block_keyword(input: &str) -> IResult<&str, Item> {
695    alt((parse_block_start, parse_else, parse_end)).parse(input)
696}
697
698/// Parse block start: `alt condition`, `opt condition`, `loop condition`, `par`, `seq`
699fn parse_block_start(input: &str) -> IResult<&str, Item> {
700    let (input, kind) = alt((
701        value(BlockKind::Alt, tag_no_case("alt")),
702        value(BlockKind::Opt, tag_no_case("opt")),
703        value(BlockKind::Loop, tag_no_case("loop")),
704        value(BlockKind::Par, tag_no_case("par")),
705        value(BlockKind::Seq, tag_no_case("seq")),
706    ))
707    .parse(input)?;
708
709    let (input, _) = space0.parse(input)?;
710    let label = input.trim().to_string();
711
712    // Return a marker block that will be processed later
713    Ok((
714        "",
715        Item::Block {
716            kind,
717            label,
718            items: vec![],
719            else_sections: vec![],
720        },
721    ))
722}
723
724/// Parse else: `else condition`
725fn parse_else(input: &str) -> IResult<&str, Item> {
726    let (input, _) = tag_no_case("else").parse(input)?;
727    let (input, _) = space0.parse(input)?;
728    let label = input.trim().to_string();
729
730    // Return a marker that will be processed during block building
731    Ok((
732        "",
733        Item::Block {
734            kind: BlockKind::Alt, // marker
735            label: format!("__ELSE__{}", label),
736            items: vec![],
737            else_sections: vec![],
738        },
739    ))
740}
741
742/// Parse end (but not "end note" or "end ref")
743fn parse_end(input: &str) -> IResult<&str, Item> {
744    let trimmed = input.trim().to_lowercase();
745    // Don't match "end note" or "end ref" - those are handled separately
746    if trimmed.starts_with("end note") || trimmed.starts_with("end ref") {
747        return Err(nom::Err::Error(nom::error::Error::new(
748            input,
749            nom::error::ErrorKind::Tag,
750        )));
751    }
752    let (_input, _) = tag_no_case("end").parse(input)?;
753    Ok((
754        "",
755        Item::Block {
756            kind: BlockKind::Alt, // marker
757            label: "__END__".to_string(),
758            items: vec![],
759            else_sections: vec![],
760        },
761    ))
762}
763
764/// Build block structure from flat list of items
765fn build_blocks(items: Vec<Item>) -> Result<Vec<Item>, ParseError> {
766    use crate::ast::ElseSection;
767
768    let mut result = Vec::new();
769    // Stack entry: (kind, label, items, else_sections, current_else_items, current_else_label, in_else_branch)
770    struct StackEntry {
771        kind: BlockKind,
772        label: String,
773        items: Vec<Item>,
774        else_sections: Vec<ElseSection>,
775        current_else_items: Vec<Item>,
776        current_else_label: Option<String>,
777        in_else_branch: bool,
778    }
779    let mut stack: Vec<StackEntry> = Vec::new();
780
781    for item in items {
782        match &item {
783            Item::Block { label, .. } if label == "__END__" => {
784                // End of block
785                if let Some(mut entry) = stack.pop() {
786                    // If we were in an else branch, finalize it
787                    if entry.in_else_branch && !entry.current_else_items.is_empty() {
788                        entry.else_sections.push(ElseSection {
789                            label: entry.current_else_label.take(),
790                            items: std::mem::take(&mut entry.current_else_items),
791                        });
792                    }
793                    let block = Item::Block {
794                        kind: entry.kind,
795                        label: entry.label,
796                        items: entry.items,
797                        else_sections: entry.else_sections,
798                    };
799                    if let Some(parent) = stack.last_mut() {
800                        if parent.in_else_branch {
801                            parent.current_else_items.push(block);
802                        } else {
803                            parent.items.push(block);
804                        }
805                    } else {
806                        result.push(block);
807                    }
808                }
809            }
810            Item::Block { label, .. } if label.starts_with("__ELSE__") => {
811                // Else marker - extract the else label
812                let else_label_text = label.strip_prefix("__ELSE__").unwrap_or("").to_string();
813                if let Some(entry) = stack.last_mut() {
814                    // If we were already in an else branch, save the current one
815                    if entry.in_else_branch && !entry.current_else_items.is_empty() {
816                        entry.else_sections.push(ElseSection {
817                            label: entry.current_else_label.take(),
818                            items: std::mem::take(&mut entry.current_else_items),
819                        });
820                    }
821                    // Start new else branch
822                    entry.in_else_branch = true;
823                    entry.current_else_items = Vec::new();
824                    entry.current_else_label = if else_label_text.is_empty() {
825                        None
826                    } else {
827                        Some(else_label_text)
828                    };
829                }
830            }
831            Item::Block {
832                kind,
833                label,
834                items,
835                else_sections,
836                ..
837            } if !label.starts_with("__") => {
838                // Check if this is a completed block (parallel/serial with items already)
839                if matches!(kind, BlockKind::Parallel | BlockKind::Serial) || !items.is_empty() {
840                    // Already a complete block, add directly
841                    let block = Item::Block {
842                        kind: *kind,
843                        label: label.clone(),
844                        items: items.clone(),
845                        else_sections: else_sections.clone(),
846                    };
847                    if let Some(parent) = stack.last_mut() {
848                        if parent.in_else_branch {
849                            parent.current_else_items.push(block);
850                        } else {
851                            parent.items.push(block);
852                        }
853                    } else {
854                        result.push(block);
855                    }
856                } else {
857                    // Block start marker
858                    stack.push(StackEntry {
859                        kind: *kind,
860                        label: label.clone(),
861                        items: Vec::new(),
862                        else_sections: Vec::new(),
863                        current_else_items: Vec::new(),
864                        current_else_label: None,
865                        in_else_branch: false,
866                    });
867                }
868            }
869            _ => {
870                // Regular item
871                if let Some(parent) = stack.last_mut() {
872                    if parent.in_else_branch {
873                        parent.current_else_items.push(item);
874                    } else {
875                        parent.items.push(item);
876                    }
877                } else {
878                    result.push(item);
879                }
880            }
881        }
882    }
883
884    Ok(result)
885}
886
887#[cfg(test)]
888mod tests {
889    use super::*;
890
891    #[test]
892    fn test_simple_message() {
893        let result = parse("Alice->Bob: Hello").unwrap();
894        assert_eq!(result.items.len(), 1);
895        match &result.items[0] {
896            Item::Message { from, to, text, .. } => {
897                assert_eq!(from, "Alice");
898                assert_eq!(to, "Bob");
899                assert_eq!(text, "Hello");
900            }
901            _ => panic!("Expected Message"),
902        }
903    }
904
905    #[test]
906    fn test_participant_decl() {
907        let result = parse("participant Alice\nactor Bob").unwrap();
908        assert_eq!(result.items.len(), 2);
909    }
910
911    #[test]
912    fn test_note() {
913        let result = parse("note over Alice: Hello").unwrap();
914        assert_eq!(result.items.len(), 1);
915        match &result.items[0] {
916            Item::Note {
917                position,
918                participants,
919                text,
920            } => {
921                assert_eq!(*position, NotePosition::Over);
922                assert_eq!(participants, &["Alice"]);
923                assert_eq!(text, "Hello");
924            }
925            _ => panic!("Expected Note"),
926        }
927    }
928
929    #[test]
930    fn test_opt_block() {
931        let result = parse("opt condition\nAlice->Bob: Hello\nend").unwrap();
932        assert_eq!(result.items.len(), 1);
933        match &result.items[0] {
934            Item::Block {
935                kind, label, items, ..
936            } => {
937                assert_eq!(*kind, BlockKind::Opt);
938                assert_eq!(label, "condition");
939                assert_eq!(items.len(), 1);
940            }
941            _ => panic!("Expected Block"),
942        }
943    }
944
945    #[test]
946    fn test_alt_else_block() {
947        let result =
948            parse("alt success\nAlice->Bob: OK\nelse failure\nAlice->Bob: Error\nend").unwrap();
949        assert_eq!(result.items.len(), 1);
950        match &result.items[0] {
951            Item::Block {
952                kind,
953                label,
954                items,
955                else_items,
956                ..
957            } => {
958                assert_eq!(*kind, BlockKind::Alt);
959                assert_eq!(label, "success");
960                assert_eq!(items.len(), 1);
961                assert!(else_items.is_some());
962                assert_eq!(else_items.as_ref().unwrap().len(), 1);
963            }
964            _ => panic!("Expected Block"),
965        }
966    }
967
968    // Task 5: Comment test
969    #[test]
970    fn test_comment() {
971        let result = parse("# This is a comment\nAlice->Bob: Hello").unwrap();
972        assert_eq!(result.items.len(), 1);
973        match &result.items[0] {
974            Item::Message { from, to, text, .. } => {
975                assert_eq!(from, "Alice");
976                assert_eq!(to, "Bob");
977                assert_eq!(text, "Hello");
978            }
979            _ => panic!("Expected Message"),
980        }
981    }
982
983    // Task 1: Multiline note test
984    #[test]
985    fn test_multiline_note() {
986        let input = r#"note left of Alice
987Line 1
988Line 2
989end note"#;
990        let result = parse(input).unwrap();
991        assert_eq!(result.items.len(), 1);
992        match &result.items[0] {
993            Item::Note {
994                position,
995                participants,
996                text,
997            } => {
998                assert_eq!(*position, NotePosition::Left);
999                assert_eq!(participants, &["Alice"]);
1000                assert_eq!(text, "Line 1\\nLine 2");
1001            }
1002            _ => panic!("Expected Note"),
1003        }
1004    }
1005
1006    // Task 2: State test
1007    #[test]
1008    fn test_state() {
1009        let result = parse("state over Server: LISTEN").unwrap();
1010        assert_eq!(result.items.len(), 1);
1011        match &result.items[0] {
1012            Item::State { participants, text } => {
1013                assert_eq!(participants, &["Server"]);
1014                assert_eq!(text, "LISTEN");
1015            }
1016            _ => panic!("Expected State"),
1017        }
1018    }
1019
1020    // Task 3: Ref test
1021    #[test]
1022    fn test_ref() {
1023        let result = parse("ref over Alice, Bob: See other diagram").unwrap();
1024        assert_eq!(result.items.len(), 1);
1025        match &result.items[0] {
1026            Item::Ref {
1027                participants, text, ..
1028            } => {
1029                assert_eq!(participants, &["Alice", "Bob"]);
1030                assert_eq!(text, "See other diagram");
1031            }
1032            _ => panic!("Expected Ref"),
1033        }
1034    }
1035
1036    #[test]
1037    fn test_ref_input_signal_multiline() {
1038        let input = r#"Alice->ref over Bob, Carol: Input signal
1039line 1
1040line 2
1041end ref-->Alice: Output signal"#;
1042        let result = parse(input).unwrap();
1043        assert_eq!(result.items.len(), 1);
1044        match &result.items[0] {
1045            Item::Ref {
1046                participants,
1047                text,
1048                input_from,
1049                input_label,
1050                output_to,
1051                output_label,
1052            } => {
1053                assert_eq!(participants, &["Bob", "Carol"]);
1054                assert_eq!(text, "line 1\\nline 2");
1055                assert_eq!(input_from.as_deref(), Some("Alice"));
1056                assert_eq!(input_label.as_deref(), Some("Input signal"));
1057                assert_eq!(output_to.as_deref(), Some("Alice"));
1058                assert_eq!(output_label.as_deref(), Some("Output signal"));
1059            }
1060            _ => panic!("Expected Ref"),
1061        }
1062    }
1063
1064    // Task 4: Option test
1065    #[test]
1066    fn test_option() {
1067        let result = parse("option footer=none").unwrap();
1068        assert_eq!(result.items.len(), 1);
1069        match &result.items[0] {
1070            Item::DiagramOption { key, value } => {
1071                assert_eq!(key, "footer");
1072                assert_eq!(value, "none");
1073            }
1074            _ => panic!("Expected DiagramOption"),
1075        }
1076    }
1077
1078    // Task 6: Quoted name with colon test
1079    #[test]
1080    fn test_quoted_name_with_colon() {
1081        let result = parse(r#"":Alice"->":Bob": Hello"#).unwrap();
1082        assert_eq!(result.items.len(), 1);
1083        match &result.items[0] {
1084            Item::Message { from, to, text, .. } => {
1085                assert_eq!(from, ":Alice");
1086                assert_eq!(to, ":Bob");
1087                assert_eq!(text, "Hello");
1088            }
1089            _ => panic!("Expected Message"),
1090        }
1091    }
1092}