Fix Mermaid shape, relationship, and state description parsing (#48489)

## What changed

- Reject unsupported flowchart shapes and Markdown strings so the terminal renderer preserves the source with an unsupported-feature notice instead of misrendering it. Keep ordinary quoted labels containing shape-like punctuation valid.
- Preserve class relationship targets beginning with `o`, such as `A --orange`, instead of consuming the first letter as an aggregation marker.
- Accumulate state aliases and descriptions in source order: use the first as the title and subsequent entries as body rows, preserving state identity and limiting body rows to 16.

## Testing

Add parser regressions for these cases and description limits, update class and state snapshots, and extend TUI snapshots to verify source preservation for unsupported flowchart syntax.

GitOrigin-RevId: c44d954312c77229a3752a0d9ada14e34a43a376
This commit is contained in:
Eric Traut
2026-09-26 17:26:07 +00:00
committed by copyberry
parent 1a89aec960
commit 6e1ab4d294
9 changed files with 151 additions and 18 deletions
+59 -6
View File
@@ -40,10 +40,12 @@ const STATE: &str = "stateDiagram-v2
Shipped --> Delivered: received
Delivered --> [*]
Rejected --> Draft: revise
Charging: Retry up to 3 times";
Charging: Retry up to 3 times
Draft: Order drafted
Draft: Awaiting submission";
const CLASS: &str = "classDiagram
class Order {
class order {
+String id
+Status status
+submit()
@@ -62,10 +64,10 @@ const CLASS: &str = "classDiagram
+String lastFour
+authorize()
}
Order \"1\" *-- \"1..*\" LineItem : contains
Order \"1\" --> \"1\" Payment : pays with
order \"1\" *-- \"1..*\" LineItem : contains
order \"1\" --> \"1\" Payment : pays with
Payment <|-- CardPayment
CardPayment ..> Order : updates";
CardPayment ..order : updates";
const ER: &str = "erDiagram
CUSTOMER ||--o{ ORDER : places
@@ -125,6 +127,32 @@ fn unicode_labels_and_later_declarations() {
insta::assert_snapshot!("LR", output);
}
}
for descriptions in [
vec!["S: Ready"],
vec!["S: Ready", "S: Working"],
vec![r#"state "Ready" as S"#, "S: Working"],
vec!["S: Ready", r#"state "Working" as S"#],
vec![r#"state "Ready" as S"#, r#"state "Working" as S"#],
] {
// References before and after descriptions must retain the same state identity.
let mut body = vec!["S --> T"];
body.extend(&descriptions);
body.push("T --> S");
let graph = super::state::parse(&body).unwrap();
let mut expected = super::state::parse(&["S --> T", "T --> S"]).unwrap();
expected.nodes[0] = super::Node {
id: "S".to_owned(),
label: "Ready".to_owned(),
shape: super::Shape::Rectangle,
declared: true,
members: if descriptions.len() == 1 {
Vec::new()
} else {
vec!["Working".to_owned()]
},
};
assert_eq!(graph, expected, "{descriptions:?}");
}
}
#[test]
@@ -164,6 +192,27 @@ fn class_relationship_endpoints() {
assert!(ports[1].contains("(many)"));
assert_eq!(output.contains('┆'), dashed);
}
for (line, target, target_tip, target_label, dashed) in [
("A --orange", "orange", '─', "", false),
("A ..o_range", "o_range", '─', "", true),
("A --o B", "B", '◇', "", false),
(r#"A ..o"many" B"#, "B", '◇', "(many)", true),
] {
let graph = super::relations::parse("classDiagram", &[line]).unwrap();
let mut expected = super::Graph::default();
let from = expected.node("A").unwrap();
let to = expected.node(target).unwrap();
expected.edges.push(super::Edge {
from,
to,
label: String::new(),
target_label: target_label.to_owned(),
source_tip: '─',
target_tip,
dashed,
});
assert_eq!(graph, expected, "{line}");
}
}
#[test]
@@ -210,7 +259,6 @@ fn rejects_incomplete_and_unsupported_families() {
"sequenceDiagram; participant A as e\u{301}",
"stateDiagram-v2; state Processing {; A-->B; }",
"stateDiagram-v2; A --> B: ok; garbage text",
"stateDiagram-v2; state \"First\" as A; state \"Second\" as A",
"stateDiagram-v2; accDescr: Order lifecycle; [*] --> Ready",
"stateDiagram; ACCDESCR: Order lifecycle; [*] --> Ready",
"stateDiagram-v2; A:::highlight; A --> B",
@@ -269,6 +317,11 @@ fn family_limits() {
format!("classDiagram; class A {{; {} }}", "+field;".repeat(17)),
format!("erDiagram; A {{; {} }}", "int id;".repeat(17)),
format!("stateDiagram-v2; {}", "A --> B;".repeat(25)),
format!("stateDiagram-v2\n{}", "S: Description\n".repeat(18)),
format!(
"stateDiagram-v2\n{}",
"state \"Description\" as S\n".repeat(18)
),
] {
assert_eq!(
render(&source, /*max_width*/ usize::MAX),
+11
View File
@@ -59,6 +59,13 @@ fn node(rest: &mut &str, graph: &mut Graph) -> Result<usize, RenderError> {
) {
return Err(RenderError::Unsupported);
}
// Longer shape delimiters must not become punctuation inside a simpler node.
if ["[(", "[[", "[/", "[\\", "{{"]
.iter()
.any(|open| rest.starts_with(open))
{
return Err(RenderError::Unsupported);
}
let declaration = match rest.chars().next() {
Some('[') => Some(("[", "]", Shape::Rectangle)),
Some('{') => Some(("{", "}", Shape::Decision)),
@@ -84,6 +91,10 @@ fn node(rest: &mut &str, graph: &mut Graph) -> Result<usize, RenderError> {
}
fn flowchart_label(label: &str) -> Result<&str, RenderError> {
// Mermaid Markdown strings require rendering beyond ordinary quoted labels.
if label.starts_with("\"`") {
return Err(RenderError::Unsupported);
}
let label = if let Some(quoted) = label.strip_prefix('"') {
quoted.strip_suffix('"').ok_or(RenderError::Unsupported)?
} else {
+6
View File
@@ -128,6 +128,12 @@ pub(super) fn parse(header: &str, body: &[&str]) -> Result<Graph, RenderError> {
let mut target_tip = '─';
for (token, tip) in [("|>", '◁'), (">", '◄'), ("*", '◆'), ("o", '◇')] {
if let Some(after) = rest.strip_prefix(token) {
// A longer identifier wins over the single-letter aggregation token.
if token == "o"
&& after.starts_with(|ch: char| ch.is_ascii_alphanumeric() || ch == '_')
{
continue;
}
target_tip = tip;
rest = after;
break;
@@ -1,10 +1,9 @@
---
source: mermaid/src/families_tests.rs
assertion_line: 100
expression: output
---
┌──────────────────┐
│ Order │
│ order │
│ ───── │
│ +String id │
│ +Status status │
@@ -12,7 +11,7 @@ expression: output
│ +cancel() │
│ ├◆─(1) contains────┐
│ ├──(1) pays with───╪─┐
│ ├◄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄╪┄╪┄┄┄┐
│ ├─┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄╪┄╪┄┄┄┐
└──────────────────┘ │ │ ┆
│ │ ┆
│ │ ┆
@@ -1,6 +1,5 @@
---
source: mermaid/src/families_tests.rs
assertion_line: 100
expression: output
---
┌─────────────────────┐
@@ -20,7 +19,9 @@ expression: output
│ │ │ │
│ │ │ │
┌─────────────────────┐ │ │ │ │
│ Draft │ │ │ │ │
│ Order drafted │ │ │ │ │
│ ───────────── │ │ │ │ │
│ Awaiting submission │ │ │ │ │
│ ├◄────────────┘ │ │ │
│ ├──submit───────┐ │ │ │
│ ├◄──────────────╪─╪───╪─╪───────┐
+17 -7
View File
@@ -1,4 +1,5 @@
//! Flat state machines, with distinct initial/final pseudostates and labeled transitions.
//! Aliases and descriptions accumulate in source order: first the title, then body rows.
use super::Direction;
use super::Edge;
@@ -32,11 +33,10 @@ pub(super) fn parse(body: &[&str]) -> Result<Graph, RenderError> {
.strip_prefix("as ")
.ok_or(RenderError::Unsupported)?;
let index = graph.node(identifier(&mut rest)?)?;
if !rest.trim().is_empty() || graph.nodes[index].declared {
if !rest.trim().is_empty() {
return Err(RenderError::Unsupported);
}
graph.nodes[index].label = label.to_owned();
graph.nodes[index].declared = true;
add_description(&mut graph.nodes[index], label)?;
continue;
}
let from = if let Some(after) = rest.strip_prefix("[*]") {
@@ -66,10 +66,7 @@ pub(super) fn parse(body: &[&str]) -> Result<Graph, RenderError> {
}
let description = description.trim();
check_label(description)?;
if graph.nodes[from].members.len() == 16 {
return Err(RenderError::Limit);
}
graph.nodes[from].members.push(description.to_owned());
add_description(&mut graph.nodes[from], description)?;
continue;
}
rest = rest
@@ -107,3 +104,16 @@ pub(super) fn parse(body: &[&str]) -> Result<Graph, RenderError> {
}
Ok(graph)
}
fn add_description(node: &mut super::Node, description: &str) -> Result<(), RenderError> {
if !node.declared {
node.label = description.to_owned();
node.declared = true;
} else {
if node.members.len() == 16 {
return Err(RenderError::Limit);
}
node.members.push(description.to_owned());
}
Ok(())
}
+27
View File
@@ -45,6 +45,22 @@ A[Review & confirm]"#;
super::parse::parse("flowchart TD", &quoted.lines().collect::<Vec<_>>()).unwrap(),
super::parse::parse("flowchart TD", &unquoted.lines().collect::<Vec<_>>()).unwrap(),
);
for (quoted, label) in [
(r#"A["(Database)"]"#, "(Database)"),
(r#"A["/Input/"]"#, "/Input/"),
] {
let graph = super::parse::parse("flowchart TD", &[quoted]).unwrap();
assert_eq!(
graph.nodes,
vec![super::Node {
id: "A".to_owned(),
label: label.to_owned(),
shape: super::Shape::Rectangle,
declared: true,
members: Vec::new(),
}]
);
}
}
#[test]
@@ -110,6 +126,17 @@ fn branches_merges_and_retry_loop() {
#[test]
fn rejects_partial_or_unsupported_input() {
for source in [
"flowchart TD; P --> Q; A[(Database)]",
"flowchart TD; P --> Q; A[/Input/]",
r"flowchart TD; P --> Q; A[\Output\]",
r"flowchart TD; P --> Q; A[/Trapezoid\]",
r"flowchart TD; P --> Q; A[\Inverse/]",
"flowchart TD; P --> Q; A[[Subroutine]]",
"flowchart TD; P --> Q; A{{Hexagon}}",
r#"flowchart TD; P --> Q; A["`hello **world**`"]"#,
r#"flowchart TD; P --> Q; A{"`Decision`"}"#,
r#"flowchart TD; P --> Q; A(["`Stadium`"])"#,
r#"flowchart TD; P --> Q; A -->|"`Caption`"| B"#,
"flowchart TD; subgraph X; A; end",
"flowchart TD; A --> B; garbage syntax",
"flowchart TD; A -.-> B",
@@ -112,6 +112,16 @@ fn mermaid_fallback_notices_preserve_source() {
for (name, source, width) in [
("invalid", "```mermaid\nflowchart LR\nA[unfinished\n```", 80),
("unsupported", "```mermaid\npie\n\"Cats\": 2\n```", 80),
(
"unsupported shape after supported edges",
"```mermaid\nflowchart TD\nP --> Q\nA[(Database)]\n```",
80,
),
(
"Markdown string after supported edges",
"```mermaid\nflowchart TD\nP --> Q\nA[\"`hello **world**`\"]\n```",
80,
),
(
"too wide",
"```mermaid\nflowchart LR\nA[Request] --> B[Reply]\n```",
@@ -16,6 +16,22 @@ pie
---
unsupported shape after supported edges
This Mermaid diagram uses features the terminal renderer doesn't support.
flowchart TD
P --> Q
A[(Database)]
---
Markdown string after supported edges
This Mermaid diagram uses features the terminal renderer doesn't support.
flowchart TD
P --> Q
A["`hello **world**`"]
---
too wide
This
Mermaid