//- mermaid & plantuml: import and export
// NOTE: import covers what people actually paste: mermaid classDiagram, flowchart / graph,
// sequenceDiagram, stateDiagram and erDiagram; plantuml class style diagrams (class, interface, enum,
// package, ...) and sequence diagrams. styling (classDef, skinparam, colors) is dropped, structure,
// labels, multiplicities, notes and click / [[links]] are kept. export writes the same subsets back.
//- small text helpers
internal const char *ix_skip_ws(const char *p) { while(*p == ' ' || *p == '\t' || *p == '\r') ++p; return p; }
internal void ix_trim(char *s)
{
u32 n = (u32)strlen(s);
while(n > 0 && (s[n - 1] == ' ' || s[n - 1] == '\t' || s[n - 1] == '\r' || s[n - 1] == ';')) s[--n] = 0;
u32 lead = 0;
while(s[lead] == ' ' || s[lead] == '\t') ++lead;
if(lead) memmove(s, s + lead, n - lead + 1);
}
internal void ix_unquote(char *s)
{
ix_trim(s);
u32 n = (u32)strlen(s);
if(n >= 2 && ((s[0] == '"' && s[n - 1] == '"') || (s[0] == '\'' && s[n - 1] == '\''))) {
memmove(s, s + 1, n - 2);
s[n - 2] = 0;
}
// mermaid / plantuml line breaks in labels become spaces
const char *breaks[] = {"
", "
", "
", "\\n"};
u32 w = 0;
for(u32 r = 0; s[r];) {
b32 hit = false;
for(u32 k = 0; k < ArrayCount(breaks); ++k) {
u64 bl = strlen(breaks[k]);
if(!strncmp(s + r, breaks[k], bl)) { s[w++] = ' '; r += (u32)bl; hit = true; break; }
}
if(!hit) s[w++] = s[r++];
}
s[w] = 0;
}
internal b32 ix_word(const char *p, const char *word)
{
u64 n = strlen(word);
return !strncasecmp(p, word, n) && (p[n] == 0 || p[n] == ' ' || p[n] == '\t' || p[n] == '\r' || p[n] == '{' || p[n] == ':' || p[n] == '"');
}
internal b32 ix_ident_char(char c)
{
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || (u8)c >= 0x80;
}
// NOTE: an id, or a "quoted name", from p. out gets the text without quotes
internal const char *ix_read_name(const char *p, char *out, u32 cap)
{
p = ix_skip_ws(p);
u32 n = 0;
if(*p == '"') {
++p;
while(*p && *p != '"') { if(n + 1 < cap) out[n++] = *p; ++p; }
if(*p == '"') ++p;
} else {
while(*p) {
if(p[0] == ':' && p[1] == ':') { if(n + 2 < cap) { out[n++] = ':'; out[n++] = ':'; } p += 2; continue; } // ns::Type
if(!(ix_ident_char(*p) || *p == '.' || *p == '~' || *p == '$')) break;
if(n + 1 < cap) out[n++] = *p;
++p;
}
}
out[n] = 0;
return p;
}
//- importer: id -> node map, container stack
typedef struct IxEntry IxEntry;
struct IxEntry {
char id[64];
s32 node;
b32 defined;
};
typedef struct Importer Importer;
struct Importer {
Diagram *d;
IxEntry *map;
u32 count;
s32 stack[16];
u32 depth;
b32 left_to_right;
};
internal s32 ix_find(Importer *ix, const char *id)
{
for(u32 i = 0; i < ix->count; ++i) if(!strcmp(ix->map[i].id, id)) return (s32)i;
return -1;
}
// NOTE: find or create the node for an id. define = this is its declaration (label / kind win)
internal s32 ix_node(Importer *ix, const char *id, const char *label, NodeKind kind, b32 define)
{
Diagram *d = ix->d;
if(!id || !id[0]) return -1;
s32 found = ix_find(ix, id);
if(found >= 0) {
IxEntry *e = &ix->map[found];
DiagramNode *n = &d->nodes[e->node];
if(define && !e->defined) {
n->kind = (u32)kind;
n->border_style = (kind == NODE_INTERFACE || kind == NODE_MODULE) ? BORDER_DASHED : BORDER_SOLID;
e->defined = true;
}
if(label && label[0]) snprintf(n->name, sizeof(n->name), "%s", label);
if(ix->depth > 0 && n->parent < 0 && ix->stack[ix->depth - 1] != e->node) n->parent = ix->stack[ix->depth - 1];
return e->node;
}
if(ix->count >= DIAGRAM_MAX_NODES) return -1;
s32 idx = diagram_add_node(d, kind, (label && label[0]) ? label : id, 0, 0);
if(idx < 0) return -1;
DiagramNode *n = &d->nodes[idx];
n->key[0] = 0;
diagram_make_key(d, n->key, sizeof(n->key), id, n->id);
if(ix->depth > 0) n->parent = ix->stack[ix->depth - 1];
IxEntry *e = &ix->map[ix->count++];
snprintf(e->id, sizeof(e->id), "%s", id);
e->node = idx;
e->defined = define;
return idx;
}
internal void ix_push(Importer *ix, s32 node)
{
if(node >= 0 && ix->depth < ArrayCount(ix->stack)) ix->stack[ix->depth++] = node;
}
internal void ix_pop(Importer *ix)
{
if(ix->depth > 0) --ix->depth;
}
// NOTE: "+name : type", "+Type name", "+method(args) Return", "-field: int [badge]" into a section
internal void ix_member(Diagram *d, s32 node, const char *line_in, const char *section_hint)
{
char line[256];
snprintf(line, sizeof(line), "%s", line_in);
ix_trim(line);
if(!line[0]) return;
// plantuml modifiers
char *mod;
while((mod = strstr(line, "{static}")) || (mod = strstr(line, "{abstract}")) || (mod = strstr(line, "{classifier}"))) {
char *close = strchr(mod, '}');
memmove(mod, close + 1, strlen(close + 1) + 1);
}
ix_trim(line);
char vis = 0;
if(strchr("+-#~", line[0]) && line[1]) { vis = line[0]; memmove(line, line + 1, strlen(line)); ix_trim(line); }
// mermaid: trailing $ = static, ()* = abstract. a type's own * (u8*) stays
u32 len = (u32)strlen(line);
while(len > 0 && (line[len - 1] == '$' || (line[len - 1] == '*' && len > 1 && line[len - 2] == ')'))) line[--len] = 0;
b32 method = strchr(line, '(') != NULL;
char name[96] = {}, type[96] = {};
if(method) {
char *close = strrchr(line, ')');
if(close) {
snprintf(type, sizeof(type), "%s", ix_skip_ws(close + 1));
close[1] = 0;
if(type[0] == ':') memmove(type, type + 1, strlen(type));
ix_trim(type);
}
snprintf(name, sizeof(name), "%s", line);
} else {
char *colon = strchr(line, ':');
if(colon) {
*colon = 0;
snprintf(name, sizeof(name), "%s", line);
snprintf(type, sizeof(type), "%s", colon + 1);
} else {
// "Type name" (mermaid / java style): the last word is the name
char *sp = strrchr(line, ' ');
if(sp) { *sp = 0; snprintf(name, sizeof(name), "%s", sp + 1); snprintf(type, sizeof(type), "%s", line); }
else snprintf(name, sizeof(name), "%s", line);
}
ix_trim(name);
ix_trim(type);
}
ix_trim(name);
if(!name[0]) return;
const char *title = section_hint ? section_hint : (method ? "methods" : "fields");
s32 sec = -1;
for(s32 s = d->nodes[node].first_section; s >= 0; s = d->sections[s].next) {
if(!strcmp(d->sections[s].title, title)) { sec = s; break; }
}
if(sec < 0) sec = diagram_add_section(d, node, title);
if(sec >= 0) diagram_add_member(d, sec, vis, name, type, "");
}
//- relationship arrows shared by mermaid class diagrams and plantuml
typedef struct IxArrow IxArrow;
struct IxArrow {
u32 kind;
b32 reverse; // the arrow points at the left side: the edge runs right -> left
};
// NOTE: arrow text with decorations and direction hints already removed, e.g. "<|--", "*--", "..>"
internal b32 ix_classify_arrow(const char *op_in, IxArrow *out)
{
char op[32];
u32 n = 0;
for(const char *c = op_in; *c && n + 1 < sizeof(op); ++c) if(*c != ' ') op[n++] = *c;
op[n] = 0;
if(n < 2) return false;
b32 dotted = strchr(op, '.') != NULL;
b32 left_tri = !strncmp(op, "<|", 2);
b32 right_tri = n >= 2 && !strcmp(op + n - 2, "|>");
b32 left_diamond_fill = op[0] == '*';
b32 right_diamond_fill = op[n - 1] == '*';
b32 left_diamond = op[0] == 'o';
b32 right_diamond = op[n - 1] == 'o';
b32 left_arrow = op[0] == '<' && !left_tri;
b32 right_arrow = op[n - 1] == '>' && !right_tri;
out->reverse = false;
if(left_tri || right_tri) {
out->kind = dotted ? EDGE_IMPLEMENTS : EDGE_INHERITANCE;
out->reverse = left_tri; // "A <|-- B": B extends A
return true;
}
if(left_diamond_fill || right_diamond_fill) { out->kind = EDGE_COMPOSITION; out->reverse = right_diamond_fill && !left_diamond_fill; return true; }
if(left_diamond || right_diamond) { out->kind = EDGE_AGGREGATION; out->reverse = right_diamond && !left_diamond; return true; }
if(left_arrow && right_arrow) { out->kind = EDGE_BIDIR; return true; }
if(strchr(op, '=')) { out->kind = EDGE_DATAFLOW; out->reverse = left_arrow; return true; }
if(left_arrow || right_arrow) { out->kind = dotted ? EDGE_DEPENDENCY : EDGE_ASSOCIATION; out->reverse = left_arrow; return true; }
if(op[n - 1] == 'x' || op[0] == 'x') { out->kind = EDGE_ASSOCIATION; out->reverse = op[0] == 'x'; return true; }
out->kind = dotted ? EDGE_DEPENDENCY : EDGE_LINK;
return true;
}
internal b32 ix_is_arrow_char(char c) { return c == '<' || c == '>' || c == '|' || c == '*' || c == 'o' || c == '.' || c == '-' || c == '=' || c == 'x'; }
// NOTE: plantuml: "-up->", "-[#red,bold]->", "-l->" lose their hints. writes the bare arrow
internal void ix_strip_arrow_hints(const char *in, char *out, u32 cap)
{
u32 n = 0;
for(const char *c = in; *c && n + 1 < cap;) {
if(*c == '[') { while(*c && *c != ']') ++c; if(*c) ++c; continue; }
if(ix_ident_char(*c) && *c != 'o' && *c != 'x') { ++c; continue; } // up / down / left / right / u d l r
if((*c == 'o' || *c == 'x') && ix_ident_char(c[1]) && c[1] != 'o' && c[1] != 'x') { ++c; continue; }
out[n++] = *c++;
}
out[n] = 0;
}
// NOTE: "A "1" *-- "many" B : label" -> parts. false when the line has no arrow
typedef struct IxRelation IxRelation;
struct IxRelation {
char left[64], right[64];
char left_card[16], right_card[16];
char label[64];
char op[32];
};
internal b32 ix_parse_relation(const char *line, IxRelation *r)
{
MemSetZero(r, sizeof(*r));
const char *p = ix_read_name(line, r->left, sizeof(r->left));
if(!r->left[0]) return false;
p = ix_skip_ws(p);
if(*p == '"') { char tmp[32]; p = ix_read_name(p, tmp, sizeof(tmp)); snprintf(r->left_card, sizeof(r->left_card), "%s", tmp); p = ix_skip_ws(p); }
// the arrow: a run of arrow chars, plantuml hints in [] or words between dashes
const char *op_start = p;
while(*p && (ix_is_arrow_char(*p) || *p == '[' || (ix_ident_char(*p) && p > op_start && (p[-1] == '-' || p[-1] == '.' || ix_ident_char(p[-1]))))) {
if(*p == '[') { while(*p && *p != ']') ++p; if(*p) ++p; continue; }
++p;
}
if(p == op_start) return false;
char raw[64];
u32 rl = (u32)Min((u64)(p - op_start), (u64)sizeof(raw) - 1);
MemCpy(raw, op_start, rl);
raw[rl] = 0;
ix_strip_arrow_hints(raw, r->op, sizeof(r->op));
if(strstr(raw, "bold") || strstr(raw, "thickness")) snprintf(r->op, sizeof(r->op), "==>"); // plantuml thick = our dataflow
if(!strstr(r->op, "--") && !strstr(r->op, "..") && !strstr(r->op, "==") && !strstr(r->op, "->") && !strstr(r->op, "<-") && !strstr(r->op, ".>") && !strstr(r->op, "<.")) return false;
p = ix_skip_ws(p);
if(*p == '"') { char tmp[32]; p = ix_read_name(p, tmp, sizeof(tmp)); snprintf(r->right_card, sizeof(r->right_card), "%s", tmp); p = ix_skip_ws(p); }
p = ix_read_name(p, r->right, sizeof(r->right));
if(!r->right[0]) return false;
p = ix_skip_ws(p);
if(*p == ':') {
snprintf(r->label, sizeof(r->label), "%s", p + 1);
ix_unquote(r->label);
// plantuml "label >" / "< label" reading direction marks
u32 ll = (u32)strlen(r->label);
if(ll > 1 && (r->label[ll - 1] == '>' || r->label[ll - 1] == '<')) { r->label[ll - 1] = 0; ix_trim(r->label); }
if(r->label[0] == '<' || r->label[0] == '>') { memmove(r->label, r->label + 1, strlen(r->label)); ix_trim(r->label); }
}
return true;
}
internal s32 ix_add_relation(Importer *ix, IxRelation *r)
{
IxArrow arrow;
if(!ix_classify_arrow(r->op, &arrow)) return -1;
s32 a = ix_node(ix, r->left, NULL, NODE_CLASS, false);
s32 b = ix_node(ix, r->right, NULL, NODE_CLASS, false);
if(a < 0 || b < 0) return -1;
s32 src = arrow.reverse ? b : a;
s32 dst = arrow.reverse ? a : b;
s32 e = diagram_add_edge(ix->d, src, dst, (EdgeKind)arrow.kind, r->label);
if(e >= 0) {
const char *sc = arrow.reverse ? r->right_card : r->left_card;
const char *dc = arrow.reverse ? r->left_card : r->right_card;
snprintf(ix->d->edges[e].src_mult, sizeof(ix->d->edges[e].src_mult), "%s", sc);
snprintf(ix->d->edges[e].dst_mult, sizeof(ix->d->edges[e].dst_mult), "%s", dc);
}
return e;
}
//- lines: comments stripped, markdown fences dropped
typedef struct IxLines IxLines;
struct IxLines {
char **line;
u32 count;
};
internal void ix_split_lines(Arena *arena, String8 text, IxLines *out, b32 mermaid)
{
u32 cap = 1;
for(u64 i = 0; i < text.size; ++i) if(text.data[i] == '\n') ++cap;
out->line = PushArray(arena, char *, cap + 1);
out->count = 0;
b32 block_comment = false;
u64 start = 0;
for(u64 i = 0; i <= text.size; ++i) {
if(i < text.size && text.data[i] != '\n') continue;
u64 len = i - start;
char *line = PushArray(arena, char, len + 1);
MemCpy(line, text.data + start, len);
line[len] = 0;
start = i + 1;
if(len && line[len - 1] == '\r') line[--len] = 0;
char *p = (char *)ix_skip_ws(line);
if(!strncmp(p, "```", 3)) continue;
if(mermaid) {
if(!strncmp(p, "%%", 2)) continue;
} else {
if(block_comment) { if(strstr(p, "'/")) block_comment = false; continue; }
if(!strncmp(p, "/'", 2)) { if(!strstr(p + 2, "'/")) block_comment = true; continue; }
if(*p == '\'') continue;
}
out->line[out->count++] = p;
}
}
//- mermaid import
internal void ix_finish(Importer *ix, b32 sequence)
{
Diagram *d = ix->d;
diagram_measure_all(d);
if(!sequence) diagram_layout_layered(d, ix->left_to_right);
diagram_fit_containers(d);
diagram_fit_lifelines(d);
diagram_rebuild_tags(d);
d->dirty = false;
}
// NOTE: flowchart node reference at p: id plus an optional shape with a label. returns the node
internal const char *mm_flow_node(Importer *ix, const char *p, s32 *out)
{
*out = -1;
p = ix_skip_ws(p);
char id[64];
u32 n = 0;
while(*p && (ix_ident_char(*p) || *p == '.' || (*p == '-' && ix_ident_char(p[1]) && n > 0 && p[1] != '-'))) { if(n + 1 < sizeof(id)) id[n++] = *p; ++p; }
id[n] = 0;
if(!n) return p;
NodeKind kind = NODE_SYSTEM;
char label[96] = {};
struct { const char *open, *close; NodeKind kind; } shapes[] = {
{"([", "])", NODE_STATE}, {"[[", "]]", NODE_MODULE}, {"[(", ")]", NODE_STORAGE}, {"((", "))", NODE_STATE},
{"{{", "}}", NODE_SYSTEM}, {"[/", "/]", NODE_INTERFACE}, {"[\\", "\\]", NODE_INTERFACE}, {"[/", "\\]", NODE_INTERFACE},
{"(", ")", NODE_STATE}, {"[", "]", NODE_SYSTEM}, {"{", "}", NODE_STATE}, {">", "]", NODE_NOTE},
};
b32 has_shape = false;
for(u32 s = 0; s < ArrayCount(shapes); ++s) {
u64 ol = strlen(shapes[s].open);
if(strncmp(p, shapes[s].open, ol)) continue;
const char *body = p + ol;
const char *end = NULL;
if(*ix_skip_ws(body) == '"') {
const char *q = strchr(ix_skip_ws(body) + 1, '"');
end = q ? strstr(q, shapes[s].close) : NULL;
} else {
end = strstr(body, shapes[s].close);
}
if(!end) continue;
u64 ll = Min((u64)(end - body), (u64)sizeof(label) - 1);
MemCpy(label, body, ll);
label[ll] = 0;
ix_unquote(label);
kind = shapes[s].kind == NODE_MODULE ? NODE_SYSTEM : shapes[s].kind;
p = end + strlen(shapes[s].close);
has_shape = true;
if(shapes[s].open[0] == '{' && shapes[s].open[1] != '{') {
// a decision: keep it visible as such
s32 node = ix_node(ix, id, label, kind, true);
if(node >= 0) snprintf(ix->d->nodes[node].stereotype, sizeof(ix->d->nodes[node].stereotype), "decision");
*out = node;
if(!strncmp(p, ":::", 3)) { p += 3; while(ix_ident_char(*p)) ++p; }
return p;
}
break;
}
*out = ix_node(ix, id, has_shape ? label : NULL, kind, has_shape);
if(!strncmp(p, ":::", 3)) { p += 3; while(ix_ident_char(*p) || *p == '-') ++p; }
return p;
}
// NOTE: a flowchart link at p ("-->", "-.->", "==>", "---", "-- text -->", "-->|text|"). false if none
internal const char *mm_flow_link(const char *p, u32 *kind, char *label, u32 label_cap, b32 *ok)
{
*ok = false;
label[0] = 0;
p = ix_skip_ws(p);
const char *s = p;
b32 left = false;
if(*p == '<' || *p == 'x' || *p == 'o') {
if(p[1] == '-' || p[1] == '=' || p[1] == '.') { left = true; ++p; } else return s;
}
if(*p != '-' && *p != '=' && *p != '.' && *p != '~') return s;
char run[16];
u32 n = 0;
while(*p && (*p == '-' || *p == '=' || *p == '.' || *p == '~' || *p == '>') && n + 1 < sizeof(run)) run[n++] = *p++;
if((*p == 'o' || *p == 'x') && !ix_ident_char(p[1])) run[n++] = *p++;
run[n] = 0;
if(n < 2 && strcmp(run, ">")) return s;
// "-- text -->": the text runs to the next arrow
if(!strchr(run, '>') && (!strcmp(run, "--") || !strcmp(run, "==") || !strcmp(run, "-."))) {
const char *end = strstr(p, "-->");
const char *e2 = strstr(p, "==>");
const char *e3 = strstr(p, ".->");
const char *e4 = strstr(p, "---");
const char *best = NULL;
const char *cands[4] = {end, e2, e3, e4};
for(u32 c = 0; c < 4; ++c) if(cands[c] && (!best || cands[c] < best)) best = cands[c];
if(best) {
u64 ll = Min((u64)(best - p), (u64)label_cap - 1);
MemCpy(label, p, ll);
label[ll] = 0;
ix_unquote(label);
n = 0;
p = best;
while(*p && (*p == '-' || *p == '=' || *p == '.' || *p == '>') && n + 1 < sizeof(run)) run[n++] = *p++;
run[n] = 0;
}
}
p = ix_skip_ws(p);
if(*p == '|') {
const char *close = strchr(p + 1, '|');
if(close) {
u64 ll = Min((u64)(close - p - 1), (u64)label_cap - 1);
MemCpy(label, p + 1, ll);
label[ll] = 0;
ix_unquote(label);
p = close + 1;
}
}
b32 arrow = strchr(run, '>') != NULL;
if(strchr(run, '=')) *kind = EDGE_DATAFLOW;
else if(strchr(run, '.')) *kind = arrow ? EDGE_DEPENDENCY : EDGE_LINK;
else if(strchr(run, '~')) *kind = EDGE_LINK;
else *kind = arrow ? EDGE_ASSOCIATION : EDGE_LINK;
if(left && arrow) *kind = EDGE_BIDIR;
*ok = true;
return p;
}
internal const char *mm_flow_group(Importer *ix, const char *q, s32 *out, u32 *count)
{
*count = 0;
for(;;) {
s32 node;
const char *next = mm_flow_node(ix, q, &node);
if(node < 0 || next == q) break;
if(*count < 16) out[(*count)++] = node;
q = ix_skip_ws(next);
if(*q == '&') { ++q; continue; }
break;
}
return q;
}
internal void mm_import_flowchart(Importer *ix, IxLines *lines, u32 first)
{
Diagram *d = ix->d;
const char *head = lines->line[first];
ix->left_to_right = strstr(head, "LR") || strstr(head, "RL");
for(u32 li = first + 1; li < lines->count; ++li) {
const char *p = lines->line[li];
if(!*p) continue;
if(ix_word(p, "subgraph")) {
char id[64] = {}, title[96] = {};
const char *q = ix_read_name(p + 8, id, sizeof(id));
q = ix_skip_ws(q);
if(*q == '[') {
const char *close = strrchr(q, ']');
if(close) { u64 l = Min((u64)(close - q - 1), (u64)sizeof(title) - 1); MemCpy(title, q + 1, l); title[l] = 0; ix_unquote(title); }
} else if(*q) {
snprintf(title, sizeof(title), "%s", q);
ix_unquote(title);
if(title[0]) { char joined[160]; snprintf(joined, sizeof(joined), "%s %s", id, title); snprintf(title, sizeof(title), "%s", joined); }
}
if(!id[0]) snprintf(id, sizeof(id), "subgraph_%u", li);
s32 m = ix_node(ix, id, title[0] ? title : id, NODE_MODULE, true);
ix_push(ix, m);
continue;
}
if(ix_word(p, "end")) { ix_pop(ix); continue; }
if(ix_word(p, "direction") || ix_word(p, "classDef") || ix_word(p, "class") || ix_word(p, "style") ||
ix_word(p, "linkStyle") || ix_word(p, "accTitle") || ix_word(p, "accDescr")) continue;
if(ix_word(p, "click")) {
// click id "url" ["tooltip"] / click id href "url"
char id[64], url[DIAGRAM_LINK_SIZE];
const char *q = ix_read_name(p + 5, id, sizeof(id));
q = ix_skip_ws(q);
if(ix_word(q, "href")) q = ix_skip_ws(q + 4);
if(*q == '"') {
ix_read_name(q, url, sizeof(url));
s32 node = ix_node(ix, id, NULL, NODE_SYSTEM, false);
if(node >= 0) snprintf(d->nodes[node].link, sizeof(d->nodes[node].link), "%s", url);
}
continue;
}
// a chain: group (link group)*, a group is node (& node)*
s32 prev[16];
u32 prev_count = 0;
const char *q = mm_flow_group(ix, p, prev, &prev_count);
for(u32 guard = 0; guard < 64 && prev_count; ++guard) {
u32 kind = EDGE_ASSOCIATION;
char label[64];
b32 ok;
const char *after = mm_flow_link(q, &kind, label, sizeof(label), &ok);
if(!ok) break;
s32 next[16];
u32 next_count = 0;
q = mm_flow_group(ix, after, next, &next_count);
if(!next_count) break;
for(u32 x = 0; x < prev_count; ++x) {
for(u32 y = 0; y < next_count; ++y) diagram_add_edge(d, prev[x], next[y], (EdgeKind)kind, label);
}
MemCpy(prev, next, sizeof(s32) * next_count);
prev_count = next_count;
}
}
ix_finish(ix, false);
}
internal void mm_import_class(Importer *ix, IxLines *lines, u32 first)
{
Diagram *d = ix->d;
s32 body = -1;
for(u32 li = first + 1; li < lines->count; ++li) {
char line[512];
snprintf(line, sizeof(line), "%s", lines->line[li]);
ix_trim(line);
const char *p = line;
if(!*p) continue;
if(body >= 0) {
if(*p == '}') { body = -1; continue; }
if(!strncmp(p, "<<", 2)) {
char st[48] = {};
const char *close = strstr(p, ">>");
if(close) { u64 l = Min((u64)(close - p - 2), (u64)sizeof(st) - 1); MemCpy(st, p + 2, l); st[l] = 0; }
if(!strcasecmp(st, "interface") || !strcasecmp(st, "abstract")) d->nodes[body].kind = NODE_INTERFACE, d->nodes[body].border_style = BORDER_DASHED;
else if(!strcasecmp(st, "enumeration") || !strcasecmp(st, "enum")) d->nodes[body].kind = NODE_ENUM;
snprintf(d->nodes[body].stereotype, sizeof(d->nodes[body].stereotype), "<<%s>>", st);
continue;
}
if(d->nodes[body].kind == NODE_ENUM && !strchr(p, '(')) ix_member(d, body, p, "values");
else ix_member(d, body, p, NULL);
continue;
}
if(ix_word(p, "direction")) { ix->left_to_right = strstr(p, "LR") || strstr(p, "RL"); continue; }
if(ix_word(p, "namespace")) {
char id[64];
ix_read_name(p + 9, id, sizeof(id));
ix_push(ix, ix_node(ix, id, id, NODE_MODULE, true));
continue;
}
if(*p == '}') { ix_pop(ix); continue; }
if(ix_word(p, "class")) {
char id[64] = {}, label[96] = {};
const char *q = ix_read_name(p + 5, id, sizeof(id));
char *tilde = strchr(id, '~');
if(tilde) { *tilde = '<'; char *t2 = strchr(tilde + 1, '~'); if(t2) { *t2 = '>'; } }
q = ix_skip_ws(q);
if(*q == '[') {
const char *close = strchr(q, ']');
if(close) { u64 l = Min((u64)(close - q - 1), (u64)sizeof(label) - 1); MemCpy(label, q + 1, l); label[l] = 0; ix_unquote(label); q = close + 1; }
}
char key[64];
snprintf(key, sizeof(key), "%s", id);
char *lt = strchr(key, '<');
if(lt) *lt = 0;
s32 node = ix_node(ix, key, label[0] ? label : id, NODE_CLASS, true);
q = ix_skip_ws(q);
if(!strncmp(q, "<<", 2)) {
const char *close = strstr(q, ">>");
if(close && node >= 0) {
char st[48] = {};
u64 l = Min((u64)(close - q - 2), (u64)sizeof(st) - 1);
MemCpy(st, q + 2, l);
if(!strcasecmp(st, "interface")) d->nodes[node].kind = NODE_INTERFACE;
snprintf(d->nodes[node].stereotype, sizeof(d->nodes[node].stereotype), "<<%s>>", st);
q = close + 2;
}
}
if(strchr(q, '{') && node >= 0) body = node;
continue;
}
if(!strncmp(p, "<<", 2)) {
// <> Name
const char *close = strstr(p, ">>");
if(close) {
char st[48] = {}, id[64];
u64 l = Min((u64)(close - p - 2), (u64)sizeof(st) - 1);
MemCpy(st, p + 2, l);
ix_read_name(close + 2, id, sizeof(id));
s32 node = ix_node(ix, id, NULL, NODE_CLASS, false);
if(node >= 0) {
if(!strcasecmp(st, "interface")) d->nodes[node].kind = NODE_INTERFACE, d->nodes[node].border_style = BORDER_DASHED;
else if(!strcasecmp(st, "enumeration") || !strcasecmp(st, "enum")) d->nodes[node].kind = NODE_ENUM;
snprintf(d->nodes[node].stereotype, sizeof(d->nodes[node].stereotype), "<<%s>>", st);
}
}
continue;
}
if(ix_word(p, "note")) {
// note for X "text" / note "text"
char target[64] = {}, text[128] = {};
const char *q = ix_skip_ws(p + 4);
if(ix_word(q, "for")) q = ix_read_name(q + 3, target, sizeof(target));
ix_read_name(q, text, sizeof(text));
char id[32];
snprintf(id, sizeof(id), "note_%u", li);
s32 note = ix_node(ix, id, "note", NODE_NOTE, true);
if(note >= 0) {
snprintf(d->nodes[note].note, sizeof(d->nodes[note].note), "%s", text);
if(target[0]) diagram_add_edge(d, note, ix_node(ix, target, NULL, NODE_CLASS, false), EDGE_LINK, "");
}
continue;
}
if(ix_word(p, "click") || ix_word(p, "link") || ix_word(p, "callback")) {
char id[64], url[DIAGRAM_LINK_SIZE] = {};
const char *q = ix_read_name(p + (ix_word(p, "callback") ? 8 : (ix_word(p, "link") ? 4 : 5)), id, sizeof(id));
q = ix_skip_ws(q);
if(ix_word(q, "href")) q = ix_skip_ws(q + 4);
if(*q == '"') {
ix_read_name(q, url, sizeof(url));
s32 node = ix_node(ix, id, NULL, NODE_CLASS, false);
if(node >= 0) snprintf(d->nodes[node].link, sizeof(d->nodes[node].link), "%s", url);
}
continue;
}
if(ix_word(p, "style") || ix_word(p, "classDef") || ix_word(p, "cssClass")) continue;
// "Name : +member" or a relation
IxRelation rel;
if(ix_parse_relation(p, &rel)) { ix_add_relation(ix, &rel); continue; }
char id[64];
const char *q = ix_read_name(p, id, sizeof(id));
q = ix_skip_ws(q);
if(id[0] && *q == ':') {
s32 node = ix_node(ix, id, NULL, NODE_CLASS, false);
if(node >= 0) ix_member(d, node, q + 1, NULL);
}
}
ix_finish(ix, false);
}
// NOTE: sequence layout done here rather than by diagram_layout_sequence: notes and fragments
// take room between messages, so y is handed out while reading
typedef struct IxSeq IxSeq;
struct IxSeq {
Importer *ix;
f32 y;
u32 number;
b32 autonumber;
s32 frame_stack[8];
f32 frame_y[8];
u32 frame_depth;
s32 *order; // lifelines in the order they appeared
u32 order_count;
s32 notes[256];
s32 note_line[256];
f32 note_y[256];
u32 note_side[256]; // 0 right, 1 left, 2 over
s32 note_line2[256];
u32 note_count;
s32 frames[64]; // finished fragments, spread over the lifelines in seq_finish
u32 frame_count;
};
internal s32 seq_participant(IxSeq *sq, const char *id, const char *label, NodeKind kind, b32 define)
{
s32 before = (s32)sq->ix->count;
s32 node = ix_node(sq->ix, id, label, kind, define);
if(node >= 0 && (s32)sq->ix->count > before) sq->order[sq->order_count++] = node;
if(node >= 0 && define) {
sq->ix->d->nodes[node].kind = (u32)kind;
sq->ix->d->nodes[node].parent = -1;
}
if(node >= 0) sq->ix->d->nodes[node].parent = -1;
return node;
}
internal void seq_message(IxSeq *sq, s32 a, s32 b, u32 kind, const char *label)
{
Diagram *d = sq->ix->d;
if(a < 0 || b < 0) return;
char text[64];
if(sq->autonumber) snprintf(text, sizeof(text), "%u. %s", ++sq->number, label);
else snprintf(text, sizeof(text), "%s", label);
s32 e = diagram_add_edge(d, a, b, (EdgeKind)kind, text);
if(e >= 0) {
d->edges[e].msg_y = sq->y;
sq->y += (a == b) ? 64.0f : 44.0f;
}
}
internal void seq_note(IxSeq *sq, const char *where, const char *text_in)
{
// "right of A", "left of A", "over A", "over A,B"
Diagram *d = sq->ix->d;
const char *p = ix_skip_ws(where);
u32 side = 0;
if(!strncasecmp(p, "right of", 8)) { side = 0; p += 8; }
else if(!strncasecmp(p, "left of", 7)) { side = 1; p += 7; }
else if(!strncasecmp(p, "over", 4)) { side = 2; p += 4; }
char a[64] = {}, b[64] = {};
p = ix_read_name(p, a, sizeof(a));
p = ix_skip_ws(p);
if(*p == ',') ix_read_name(p + 1, b, sizeof(b));
s32 la = seq_participant(sq, a, NULL, NODE_LIFELINE, false);
s32 lb = b[0] ? seq_participant(sq, b, NULL, NODE_LIFELINE, false) : -1;
if(la < 0 || sq->note_count >= ArrayCount(sq->notes)) return;
char id[32];
snprintf(id, sizeof(id), "note_%u", sq->note_count + 1);
s32 note = ix_node(sq->ix, id, "note", NODE_NOTE, true);
if(note < 0) return;
d->nodes[note].parent = -1;
char text[128];
snprintf(text, sizeof(text), "%s", text_in);
ix_unquote(text);
snprintf(d->nodes[note].name, sizeof(d->nodes[note].name), "%s", text);
u32 k = sq->note_count++;
sq->notes[k] = note; sq->note_line[k] = la; sq->note_line2[k] = lb; sq->note_side[k] = side; sq->note_y[k] = sq->y - 14.0f;
sq->y += 52.0f;
}
internal void seq_frame_begin(IxSeq *sq, const char *kind, const char *text)
{
Diagram *d = sq->ix->d;
if(sq->frame_depth >= ArrayCount(sq->frame_stack)) return;
char id[32], name[96];
snprintf(id, sizeof(id), "frame_%u", (u32)d->node_count + 1);
snprintf(name, sizeof(name), "%s%s%s", kind, text[0] ? " " : "", text);
s32 f = ix_node(sq->ix, id, name, NODE_MODULE, true);
if(f < 0) return;
d->nodes[f].parent = -1;
sq->frame_stack[sq->frame_depth] = f;
sq->frame_y[sq->frame_depth] = sq->y - 26.0f;
++sq->frame_depth;
sq->y += 22.0f;
}
internal void seq_frame_end(IxSeq *sq)
{
if(!sq->frame_depth) return;
--sq->frame_depth;
s32 f = sq->frame_stack[sq->frame_depth];
DiagramNode *n = &sq->ix->d->nodes[f];
n->y = sq->frame_y[sq->frame_depth];
n->h = (sq->y - 10.0f) - n->y;
n->manual_size = true;
n->pinned = true;
if(sq->frame_count < ArrayCount(sq->frames)) sq->frames[sq->frame_count++] = f;
sq->y += 16.0f;
}
internal void seq_finish(IxSeq *sq)
{
Diagram *d = sq->ix->d;
diagram_measure_all(d);
f32 head = 0.0f;
for(u32 i = 0; i < sq->order_count; ++i) head = Max(head, d->nodes[sq->order[i]].header_h);
f32 x = 40.0f;
for(u32 i = 0; i < sq->order_count; ++i) {
DiagramNode *n = &d->nodes[sq->order[i]];
n->x = x;
n->y = 40.0f + head - n->header_h;
x += n->w + 80.0f;
}
// NOTE: messages were numbered from y = 0 while reading, move them below the heads
f32 shift = 40.0f + head + 40.0f;
for(u32 e = 0; e < d->edge_count; ++e) if(d->edges[e].alive && diagram_edge_is_message(d, (s32)e)) d->edges[e].msg_y += shift;
for(u32 k = 0; k < sq->note_count; ++k) {
DiagramNode *n = &d->nodes[sq->notes[k]];
DiagramNode *a = &d->nodes[sq->note_line[k]];
f32 cx = a->x + a->w * 0.5f;
diagram_measure_node(d, sq->notes[k]);
if(sq->note_side[k] == 0) n->x = cx + 14.0f;
else if(sq->note_side[k] == 1) n->x = cx - 14.0f - n->w;
else {
f32 cx2 = (sq->note_line2[k] >= 0) ? d->nodes[sq->note_line2[k]].x + d->nodes[sq->note_line2[k]].w * 0.5f : cx;
n->x = (cx + cx2) * 0.5f - n->w * 0.5f;
}
n->y = sq->note_y[k] + shift;
}
f32 x0 = 1e9f, x1 = -1e9f;
for(u32 i = 0; i < sq->order_count; ++i) { x0 = Min(x0, d->nodes[sq->order[i]].x); x1 = Max(x1, d->nodes[sq->order[i]].x + d->nodes[sq->order[i]].w); }
// NOTE: a fragment spans the lifelines its messages touch (all of them when it has none),
// nested ones sit a little inside their parent
for(u32 k = 0; k < sq->frame_count; ++k) {
DiagramNode *n = &d->nodes[sq->frames[k]];
f32 top = n->y, bottom = n->y + n->h;
f32 fx0 = 1e9f, fx1 = -1e9f;
for(u32 e = 0; e < d->edge_count; ++e) {
DiagramEdge *ed = &d->edges[e];
if(!ed->alive || !diagram_edge_is_message(d, (s32)e) || ed->msg_y < top || ed->msg_y > bottom) continue;
DiagramNode *a = &d->nodes[ed->src], *b = &d->nodes[ed->dst];
fx0 = Min(fx0, Min(a->x + a->w * 0.5f, b->x + b->w * 0.5f));
fx1 = Max(fx1, Max(a->x + a->w * 0.5f, b->x + b->w * 0.5f) + (ed->src == ed->dst ? 60.0f : 0.0f));
}
if(fx0 > fx1) { fx0 = x0 + 40.0f; fx1 = x1 - 40.0f; }
f32 inset = 0.0f;
for(u32 j = 0; j < sq->frame_count; ++j) {
DiagramNode *o = &d->nodes[sq->frames[j]];
if(j != k && o->y <= n->y && o->y + o->h >= n->y + n->h) inset += 12.0f;
}
n->x = fx0 - 70.0f + inset;
n->w = (fx1 - fx0) + 140.0f - inset * 2.0f;
n->y += shift;
n->min_w = Min(n->min_w, n->w);
n->min_h = Min(n->min_h, n->h);
}
diagram_fit_lifelines(d);
diagram_rebuild_tags(d);
d->dirty = false;
}
internal void mm_import_sequence(Importer *ix, IxLines *lines, u32 first, Arena *arena)
{
IxSeq *sq = PushStructZero(arena, IxSeq);
sq->ix = ix;
sq->order = PushArray(arena, s32, DIAGRAM_MAX_NODES);
for(u32 li = first + 1; li < lines->count; ++li) {
char line[512];
snprintf(line, sizeof(line), "%s", lines->line[li]);
ix_trim(line);
const char *p = line;
if(!*p) continue;
if(ix_word(p, "participant") || ix_word(p, "actor")) {
b32 actor = ix_word(p, "actor");
char id[64] = {}, label[96] = {};
const char *q = ix_read_name(p + (actor ? 5 : 11), id, sizeof(id));
q = ix_skip_ws(q);
if(ix_word(q, "as")) { snprintf(label, sizeof(label), "%s", q + 2); ix_unquote(label); }
seq_participant(sq, id, label[0] ? label : id, actor ? NODE_ACTOR : NODE_LIFELINE, true);
continue;
}
if(ix_word(p, "autonumber")) { sq->autonumber = true; continue; }
if(ix_word(p, "note")) {
const char *colon = strchr(p, ':');
if(colon) {
char where[128];
u64 l = Min((u64)(colon - p - 4), (u64)sizeof(where) - 1);
MemCpy(where, p + 4, l);
where[l] = 0;
seq_note(sq, where, colon + 1);
}
continue;
}
const char *frames[] = {"loop", "alt", "opt", "par", "critical", "break", "rect", "box"};
b32 framed = false;
for(u32 f = 0; f < ArrayCount(frames); ++f) {
if(ix_word(p, frames[f])) {
if(f < 6) seq_frame_begin(sq, frames[f], ix_skip_ws(p + strlen(frames[f])));
else seq_frame_begin(sq, "", ""); // rect / box: an unnamed frame
framed = true;
break;
}
}
if(framed) continue;
if(ix_word(p, "else") || ix_word(p, "and") || ix_word(p, "option")) { sq->y += 24.0f; continue; }
if(ix_word(p, "end")) { seq_frame_end(sq); continue; }
if(ix_word(p, "activate") || ix_word(p, "deactivate") || ix_word(p, "title") || ix_word(p, "links") || ix_word(p, "link") || ix_word(p, "create") || ix_word(p, "destroy")) continue;
// A->>B: text, A-->>B, A->B, A-->B, A-)B, A--)B, A-xB, A--xB
char a[64] = {}, b[64] = {};
const char *q = ix_read_name(p, a, sizeof(a));
if(!a[0]) continue;
q = ix_skip_ws(q);
const char *ops[] = {"-->>", "->>", "--)", "-)", "--x", "-x", "-->", "->", "<<-->>", "<<->>"};
u32 kinds[] = {EDGE_REPLY, EDGE_MESSAGE, EDGE_ASYNC, EDGE_ASYNC, EDGE_REPLY, EDGE_MESSAGE, EDGE_REPLY, EDGE_MESSAGE, EDGE_BIDIR, EDGE_BIDIR};
u32 kind = EDGE_KIND_COUNT;
for(u32 o = 0; o < ArrayCount(ops); ++o) {
u64 ol = strlen(ops[o]);
if(!strncmp(q, ops[o], ol)) { kind = kinds[o]; q += ol; break; }
}
if(kind == EDGE_KIND_COUNT) continue;
q = ix_skip_ws(q);
if(*q == '+' || *q == '-') ++q;
q = ix_read_name(q, b, sizeof(b));
q = ix_skip_ws(q);
char label[96] = {};
if(*q == ':') { snprintf(label, sizeof(label), "%s", q + 1); ix_unquote(label); }
s32 la = seq_participant(sq, a, NULL, NODE_LIFELINE, false);
s32 lb = seq_participant(sq, b, NULL, NODE_LIFELINE, false);
seq_message(sq, la, lb, kind, label);
}
while(sq->frame_depth) seq_frame_end(sq);
seq_finish(sq);
}
internal void mm_import_state(Importer *ix, IxLines *lines, u32 first)
{
Diagram *d = ix->d;
u32 starts = 0;
for(u32 li = first + 1; li < lines->count; ++li) {
char line[512];
snprintf(line, sizeof(line), "%s", lines->line[li]);
ix_trim(line);
const char *p = line;
if(!*p) continue;
if(ix_word(p, "direction")) { ix->left_to_right = strstr(p, "LR") || strstr(p, "RL"); continue; }
if(*p == '}') { ix_pop(ix); continue; }
if(ix_word(p, "state")) {
char id[64] = {}, label[96] = {};
const char *q = ix_skip_ws(p + 5);
if(*q == '"') {
q = ix_read_name(q, label, sizeof(label));
q = ix_skip_ws(q);
if(ix_word(q, "as")) q = ix_read_name(q + 2, id, sizeof(id));
} else {
q = ix_read_name(q, id, sizeof(id));
}
if(!id[0]) continue;
q = ix_skip_ws(q);
if(*q == '{') { ix_push(ix, ix_node(ix, id, label[0] ? label : id, NODE_MODULE, true)); continue; }
s32 node = ix_node(ix, id, label[0] ? label : NULL, NODE_STATE, true);
if(*q == ':' && node >= 0) { snprintf(d->nodes[node].note, sizeof(d->nodes[node].note), "%s", q + 1); ix_trim(d->nodes[node].note); }
if(strstr(q, "<>") && node >= 0) snprintf(d->nodes[node].stereotype, sizeof(d->nodes[node].stereotype), "choice");
continue;
}
if(ix_word(p, "note") || ix_word(p, "classDef") || ix_word(p, "class")) continue;
// A --> B : label, with [*] for start / end
const char *arrow = strstr(p, "-->");
if(arrow) {
char a[64] = {}, b[64] = {}, label[64] = {};
u64 al = Min((u64)(arrow - p), (u64)sizeof(a) - 1);
MemCpy(a, p, al);
ix_trim(a);
const char *rest = arrow + 3;
const char *colon = strchr(rest, ':');
u64 bl = Min((u64)((colon ? colon : rest + strlen(rest)) - rest), (u64)sizeof(b) - 1);
MemCpy(b, rest, bl);
ix_trim(b);
if(colon) { snprintf(label, sizeof(label), "%s", colon + 1); ix_unquote(label); }
// NOTE: every [*] is its own start or end dot (one per container is what mermaid means)
char ida[64], idb[64];
snprintf(ida, sizeof(ida), "%s", a);
snprintf(idb, sizeof(idb), "%s", b);
if(!strcmp(a, "[*]")) snprintf(ida, sizeof(ida), "start_%u", ix->depth ? (u32)ix->stack[ix->depth - 1] : 0u);
if(!strcmp(b, "[*]")) snprintf(idb, sizeof(idb), "end_%u", ix->depth ? (u32)ix->stack[ix->depth - 1] : 0u);
s32 na = ix_node(ix, ida, !strcmp(a, "[*]") ? "start" : NULL, NODE_STATE, !strcmp(a, "[*]"));
s32 nb = ix_node(ix, idb, !strcmp(b, "[*]") ? "end" : NULL, NODE_STATE, !strcmp(b, "[*]"));
if(!strcmp(a, "[*]") && na >= 0) { snprintf(d->nodes[na].stereotype, sizeof(d->nodes[na].stereotype), "initial"); ++starts; }
if(!strcmp(b, "[*]") && nb >= 0) snprintf(d->nodes[nb].stereotype, sizeof(d->nodes[nb].stereotype), "final");
diagram_add_edge(d, na, nb, EDGE_ASSOCIATION, label);
continue;
}
// "A : description"
char id[64];
const char *q = ix_read_name(p, id, sizeof(id));
q = ix_skip_ws(q);
if(id[0] && *q == ':') {
s32 node = ix_node(ix, id, NULL, NODE_STATE, false);
if(node >= 0) { snprintf(d->nodes[node].note, sizeof(d->nodes[node].note), "%s", q + 1); ix_trim(d->nodes[node].note); }
}
}
ix_finish(ix, false);
}
internal const char *er_card(const char *c, b32 left)
{
// left side reads outward-in ("|o", "||", "}o", "}|"), right side inward-out ("o|", "||", "o{", "|{")
if(!strncmp(c, "||", 2)) return "1";
if(left ? !strncmp(c, "|o", 2) : !strncmp(c, "o|", 2)) return "0..1";
if(left ? !strncmp(c, "}|", 2) : !strncmp(c, "|{", 2)) return "1..*";
if(left ? !strncmp(c, "}o", 2) : !strncmp(c, "o{", 2)) return "0..*";
return "";
}
// NOTE: er entity names may hold '-' ("LINE-ITEM"), the relation is always space separated
internal const char *er_read_name(const char *p, char *out, u32 cap)
{
p = ix_skip_ws(p);
if(*p == '"') return ix_read_name(p, out, cap);
u32 n = 0;
while(*p && *p != ' ' && *p != '\t' && *p != '{' && *p != ':') { if(n + 1 < cap) out[n++] = *p; ++p; }
out[n] = 0;
return p;
}
internal void mm_import_er(Importer *ix, IxLines *lines, u32 first)
{
Diagram *d = ix->d;
s32 body = -1;
for(u32 li = first + 1; li < lines->count; ++li) {
char line[512];
snprintf(line, sizeof(line), "%s", lines->line[li]);
ix_trim(line);
const char *p = line;
if(!*p) continue;
if(body >= 0) {
if(*p == '}') { body = -1; continue; }
// "type name PK "comment""
char type[64] = {}, name[64] = {}, key[16] = {};
const char *q = ix_read_name(p, type, sizeof(type));
q = ix_read_name(q, name, sizeof(name));
q = ix_skip_ws(q);
if(!strncmp(q, "PK", 2) || !strncmp(q, "FK", 2) || !strncmp(q, "UK", 2)) { MemCpy(key, q, 2); }
s32 sec = d->nodes[body].first_section;
if(sec < 0) sec = diagram_add_section(d, body, "attributes");
if(name[0]) diagram_add_member(d, sec, 0, name, type, key);
continue;
}
char a[64] = {};
const char *q = er_read_name(p, a, sizeof(a));
q = ix_skip_ws(q);
if(*q == '{') { body = ix_node(ix, a, NULL, NODE_STRUCT, true); continue; }
// A ||--o{ B : label
if(strlen(q) >= 6 && (q[2] == '-' || q[2] == '.')) {
char lc[3] = {q[0], q[1], 0}, rc[3] = {};
const char *mid = q + 2;
while(*mid == '-' || *mid == '.') ++mid;
rc[0] = mid[0];
rc[1] = mid[0] ? mid[1] : 0;
const char *r = mid + 2;
char b[64] = {}, label[64] = {};
r = er_read_name(r, b, sizeof(b));
r = ix_skip_ws(r);
if(*r == ':') { snprintf(label, sizeof(label), "%s", r + 1); ix_unquote(label); }
s32 na = ix_node(ix, a, NULL, NODE_STRUCT, false);
s32 nb = ix_node(ix, b, NULL, NODE_STRUCT, false);
s32 e = diagram_add_edge(d, na, nb, q[2] == '.' ? EDGE_DEPENDENCY : EDGE_ASSOCIATION, label);
if(e >= 0) {
snprintf(d->edges[e].src_mult, sizeof(d->edges[e].src_mult), "%s", er_card(lc, true));
snprintf(d->edges[e].dst_mult, sizeof(d->edges[e].dst_mult), "%s", er_card(rc, false));
}
continue;
}
if(a[0]) ix_node(ix, a, NULL, NODE_STRUCT, true);
}
ix_finish(ix, false);
}
internal b32 diagram_import_mermaid(Diagram *d, String8 text)
{
ScratchArena scratch = ScratchGet();
IxLines lines;
ix_split_lines(scratch.arena, text, &lines, true);
diagram_clear(d);
Importer ix = {};
ix.d = d;
ix.map = PushArray(scratch.arena, IxEntry, DIAGRAM_MAX_NODES);
snprintf(d->title, sizeof(d->title), "Imported diagram");
// optional --- title: X --- front matter
u32 first = 0;
if(lines.count && !strcmp(lines.line[0], "---")) {
for(first = 1; first < lines.count && strcmp(lines.line[first], "---"); ++first) {
const char *p = lines.line[first];
if(!strncmp(p, "title:", 6)) { snprintf(d->title, sizeof(d->title), "%s", ix_skip_ws(p + 6)); ix_trim(d->title); }
}
++first;
}
while(first < lines.count && !lines.line[first][0]) ++first;
if(first >= lines.count) { scratch_end(&scratch); return false; }
const char *head = lines.line[first];
if(ix_word(head, "classDiagram") || ix_word(head, "classDiagram-v2")) mm_import_class(&ix, &lines, first);
else if(ix_word(head, "sequenceDiagram")) mm_import_sequence(&ix, &lines, first, scratch.arena);
else if(!strncmp(head, "stateDiagram", 12)) mm_import_state(&ix, &lines, first);
else if(ix_word(head, "erDiagram")) mm_import_er(&ix, &lines, first);
else if(ix_word(head, "flowchart") || ix_word(head, "graph")) mm_import_flowchart(&ix, &lines, first);
else { scratch_end(&scratch); return false; }
scratch_end(&scratch);
return d->live_nodes > 0;
}
//- plantuml import
internal b32 puml_is_sequence(IxLines *lines)
{
b32 participants = false, messages = false;
for(u32 i = 0; i < lines->count; ++i) {
const char *p = lines->line[i];
if(ix_word(p, "class") || ix_word(p, "interface") || ix_word(p, "enum") || ix_word(p, "abstract") || ix_word(p, "package") ||
ix_word(p, "namespace") || ix_word(p, "entity") || ix_word(p, "component") || ix_word(p, "annotation") || ix_word(p, "object") ||
ix_word(p, "usecase") || ix_word(p, "state")) return false;
if(ix_word(p, "participant") || ix_word(p, "actor") || ix_word(p, "boundary") || ix_word(p, "control") ||
ix_word(p, "collections") || ix_word(p, "activate") || ix_word(p, "autonumber")) participants = true;
if(strstr(p, "->") || strstr(p, "<-")) messages = true;
}
return participants || messages;
}
internal void puml_import_sequence(Importer *ix, IxLines *lines, Arena *arena)
{
Diagram *d = ix->d;
IxSeq *sq = PushStructZero(arena, IxSeq);
sq->ix = ix;
sq->order = PushArray(arena, s32, DIAGRAM_MAX_NODES);
const char *decls[] = {"participant", "actor", "boundary", "control", "entity", "database", "collections", "queue"};
for(u32 li = 0; li < lines->count; ++li) {
char line[512];
snprintf(line, sizeof(line), "%s", lines->line[li]);
ix_trim(line);
const char *p = line;
if(!*p || *p == '@') continue;
if(ix_word(p, "title")) { snprintf(d->title, sizeof(d->title), "%s", ix_skip_ws(p + 5)); continue; }
b32 declared = false;
for(u32 k = 0; k < ArrayCount(decls); ++k) {
if(!ix_word(p, decls[k])) continue;
// participant "Long Name" as L / participant L as "Long Name" / participant L
char a[96] = {}, b[96] = {};
const char *q = ix_read_name(p + strlen(decls[k]), a, sizeof(a));
q = ix_skip_ws(q);
if(ix_word(q, "as")) ix_read_name(q + 2, b, sizeof(b));
const char *id = b[0] ? b : a, *label = a;
if(b[0] && strchr(p, '"') && *ix_skip_ws(p + strlen(decls[k])) != '"') { id = a; label = b; }
s32 node = seq_participant(sq, id, label, k == 1 ? NODE_ACTOR : NODE_LIFELINE, true);
if(node >= 0 && k > 1) snprintf(d->nodes[node].stereotype, sizeof(d->nodes[node].stereotype), "%s", decls[k]);
declared = true;
break;
}
if(declared) continue;
if(ix_word(p, "autonumber")) { sq->autonumber = true; continue; }
if(ix_word(p, "note") || ix_word(p, "hnote") || ix_word(p, "rnote")) {
const char *q = ix_skip_ws(p + (p[0] == 'n' ? 4 : 5));
const char *colon = strchr(q, ':');
char where[128] = {};
char text[256] = {};
if(colon) {
u64 l = Min((u64)(colon - q), (u64)sizeof(where) - 1);
MemCpy(where, q, l);
snprintf(text, sizeof(text), "%s", colon + 1);
} else {
// multi line note until "end note"
snprintf(where, sizeof(where), "%s", q);
u32 tl = 0;
for(++li; li < lines->count && !ix_word(lines->line[li], "end"); ++li) {
tl += (u32)snprintf(text + tl, sizeof(text) - tl, "%s%s", tl ? " " : "", lines->line[li]);
if(tl >= sizeof(text) - 1) break;
}
}
seq_note(sq, where, text);
continue;
}
const char *frames[] = {"alt", "opt", "loop", "par", "break", "critical", "group"};
b32 framed = false;
for(u32 f = 0; f < ArrayCount(frames); ++f) {
if(ix_word(p, frames[f])) { seq_frame_begin(sq, frames[f], ix_skip_ws(p + strlen(frames[f]))); framed = true; break; }
}
if(framed) continue;
if(ix_word(p, "else")) { sq->y += 24.0f; continue; }
if(ix_word(p, "end")) { seq_frame_end(sq); continue; }
if(!strncmp(p, "==", 2) || !strncmp(p, "...", 3) || !strncmp(p, "|||", 3) || ix_word(p, "activate") || ix_word(p, "deactivate") ||
ix_word(p, "destroy") || ix_word(p, "skinparam") || ix_word(p, "hide") || ix_word(p, "show") || ix_word(p, "return")) continue;
// A -> B : text (arrows: -> --> ->> -\ -/ <- <-- and [#color] decorations)
char a[64] = {}, b[64] = {};
const char *q = ix_read_name(p, a, sizeof(a));
if(!a[0]) continue;
q = ix_skip_ws(q);
const char *op = q;
while(*q && (strchr("<>-./\\x[]#o", *q) || (*q != ' ' && q > op && q[-1] == '['))) {
if(*q == '[') { while(*q && *q != ']') ++q; if(*q) ++q; continue; }
++q;
}
char arrow[32] = {};
u32 al = 0;
for(const char *c = op; c < q && al + 1 < sizeof(arrow); ++c) {
if(*c == '[') { while(c < q && *c != ']') ++c; continue; }
arrow[al++] = *c;
}
arrow[al] = 0;
if(!strstr(arrow, "->") && !strstr(arrow, "<-") && !strstr(arrow, "-\\") && !strstr(arrow, "-/")) continue;
q = ix_skip_ws(q);
if(*q == '+' || *q == '-' || *q == '*' || *q == '!') ++q;
q = ix_read_name(q, b, sizeof(b));
q = ix_skip_ws(q);
char label[96] = {};
if(*q == ':') { snprintf(label, sizeof(label), "%s", q + 1); ix_unquote(label); }
b32 back = arrow[0] == '<';
b32 dashed = strstr(arrow, "--") != NULL;
b32 async = strstr(arrow, ">>") || strstr(arrow, "<<") || strchr(arrow, '\\') || strchr(arrow, '/');
u32 kind = async ? EDGE_ASYNC : (dashed ? EDGE_REPLY : EDGE_MESSAGE);
s32 la = seq_participant(sq, a, NULL, NODE_LIFELINE, false);
s32 lb = seq_participant(sq, b, NULL, NODE_LIFELINE, false);
if(back) seq_message(sq, lb, la, kind, label);
else seq_message(sq, la, lb, kind, label);
}
while(sq->frame_depth) seq_frame_end(sq);
seq_finish(sq);
}
internal NodeKind puml_kind(const char *word, b32 *container)
{
*container = false;
struct { const char *w; NodeKind k; b32 c; } map[] = {
{"abstract class", NODE_INTERFACE, 0}, {"abstract", NODE_INTERFACE, 0}, {"class", NODE_CLASS, 0}, {"interface", NODE_INTERFACE, 0},
{"enum", NODE_ENUM, 0}, {"annotation", NODE_INTERFACE, 0}, {"entity", NODE_STRUCT, 0}, {"struct", NODE_STRUCT, 0},
{"object", NODE_STRUCT, 0}, {"protocol", NODE_INTERFACE, 0}, {"record", NODE_STRUCT, 0}, {"exception", NODE_CLASS, 0},
{"component", NODE_SYSTEM, 0}, {"node", NODE_SYSTEM, 1}, {"database", NODE_STORAGE, 0}, {"queue", NODE_STORAGE, 0},
{"storage", NODE_STORAGE, 0}, {"actor", NODE_ACTOR, 0}, {"usecase", NODE_STATE, 0}, {"state", NODE_STATE, 0},
{"package", NODE_MODULE, 1}, {"namespace", NODE_MODULE, 1}, {"rectangle", NODE_MODULE, 1}, {"folder", NODE_MODULE, 1},
{"frame", NODE_MODULE, 1}, {"cloud", NODE_MODULE, 1}, {"artifact", NODE_STORAGE, 0}, {"card", NODE_NOTE, 0},
{"file", NODE_STORAGE, 0}, {"agent", NODE_SYSTEM, 0}, {"boundary", NODE_SYSTEM, 0}, {"control", NODE_SYSTEM, 0},
};
for(u32 i = 0; i < ArrayCount(map); ++i) {
if(ix_word(word, map[i].w)) { *container = map[i].c; return map[i].k; }
}
return NODE_KIND_COUNT;
}
internal void puml_import_class(Importer *ix, IxLines *lines)
{
Diagram *d = ix->d;
s32 body = -1;
char section[40] = {};
u32 body_depth = 0;
for(u32 li = 0; li < lines->count; ++li) {
char line[512];
snprintf(line, sizeof(line), "%s", lines->line[li]);
ix_trim(line);
const char *p = line;
if(!*p || *p == '@') continue;
if(body >= 0) {
if(*p == '}') { if(body_depth > 0) --body_depth; else { body = -1; } continue; }
if(*p == '{') { ++body_depth; continue; }
// separators: -- title --, .. title .., == title ==, __ title __
if((p[0] == '-' && p[1] == '-') || (p[0] == '.' && p[1] == '.') || (p[0] == '=' && p[1] == '=') || (p[0] == '_' && p[1] == '_')) {
// the title sits between the runs: "-- memory (cache-isolated) --"
char t[40] = {};
const char *c = p;
while(*c == p[0]) ++c;
u32 n = 0;
for(; *c && n + 1 < sizeof(t); ++c) t[n++] = *c;
t[n] = 0;
while(n > 0 && (t[n - 1] == p[0] || t[n - 1] == ' ')) t[--n] = 0;
ix_trim(t);
snprintf(section, sizeof(section), "%s", t[0] ? t : "members");
continue;
}
if(d->nodes[body].kind == NODE_ENUM && !strchr(p, '(')) ix_member(d, body, p, section[0] ? section : "values");
else ix_member(d, body, p, section[0] ? section : NULL);
continue;
}
if(*p == '}') { ix_pop(ix); continue; }
if(ix_word(p, "title")) { snprintf(d->title, sizeof(d->title), "%s", ix_skip_ws(p + 5)); continue; }
if(ix_word(p, "skinparam") || ix_word(p, "hide") || ix_word(p, "show") || ix_word(p, "left") || ix_word(p, "top") ||
ix_word(p, "allowmixing") || ix_word(p, "set") || ix_word(p, "!include") || p[0] == '!') continue;
if(ix_word(p, "note")) {
// note "text" as N / note top of A : text / note left of A ... end note
char text[256] = {}, target[64] = {}, id[64] = {};
const char *q = ix_skip_ws(p + 4);
const char *colon = strchr(q, ':');
if(*q == '"') {
q = ix_read_name(q, text, sizeof(text));
q = ix_skip_ws(q);
if(ix_word(q, "as")) ix_read_name(q + 2, id, sizeof(id));
} else {
const char *of = strstr(q, " of ");
if(of) ix_read_name(of + 4, target, sizeof(target));
if(colon) snprintf(text, sizeof(text), "%s", colon + 1);
else {
u32 tl = 0;
for(++li; li < lines->count && !ix_word(lines->line[li], "end"); ++li) {
tl += (u32)snprintf(text + tl, sizeof(text) - tl, "%s%s", tl ? " " : "", lines->line[li]);
if(tl >= sizeof(text) - 1) break;
}
}
}
ix_unquote(text);
if(!id[0]) snprintf(id, sizeof(id), "note_%u", li);
s32 note = ix_node(ix, id, "note", NODE_NOTE, true);
if(note >= 0) {
snprintf(d->nodes[note].note, sizeof(d->nodes[note].note), "%s", text);
if(target[0]) diagram_add_edge(d, note, ix_node(ix, target, NULL, NODE_CLASS, false), EDGE_LINK, "");
}
continue;
}
// NOTE: relations first: ids like "frame" or "node" are also keywords
IxRelation rel;
if(ix_parse_relation(p, &rel)) { ix_add_relation(ix, &rel); continue; }
b32 container = false;
NodeKind kind = puml_kind(p, &container);
if(kind != NODE_KIND_COUNT) {
const char *q = p;
if(ix_word(q, "abstract")) { q += 8; q = ix_skip_ws(q); if(ix_word(q, "class")) q += 5; }
else { while(*q && *q != ' ' && *q != '\t' && *q != '"') ++q; }
char a[96] = {}, b[96] = {};
b32 first_quoted = *ix_skip_ws(q) == '"';
q = ix_read_name(q, a, sizeof(a));
char *lt = strchr(a, '<');
if(lt) *lt = 0;
q = ix_skip_ws(q);
if(*q == '<' && q[1] != '<') { while(*q && *q != '>') ++q; if(*q) ++q; q = ix_skip_ws(q); } // generics
if(ix_word(q, "as")) { q = ix_read_name(q + 2, b, sizeof(b)); q = ix_skip_ws(q); }
// class "Long Name" as K: id K. class K as "Long Name": id K too
const char *id = a, *label = a;
if(b[0]) { id = first_quoted ? b : a; label = first_quoted ? a : b; }
char stereo[48] = {}, url[DIAGRAM_LINK_SIZE] = {};
const char *st = strstr(q, "<<");
if(st) {
const char *close = strstr(st, ">>");
if(close) { u64 l = Min((u64)(close - st - 2), (u64)sizeof(stereo) - 1); MemCpy(stereo, st + 2, l); }
}
const char *lk = strstr(q, "[[");
if(lk) {
const char *close = strstr(lk, "]]");
if(close) {
u64 l = Min((u64)(close - lk - 2), (u64)sizeof(url) - 1);
MemCpy(url, lk + 2, l);
url[l] = 0;
char *sp = strchr(url, ' ');
if(sp) *sp = 0; // [[url tooltip]]
char *br = strchr(url, '{');
if(br) *br = 0;
}
}
s32 node = ix_node(ix, id, label, kind, true);
if(node < 0) continue;
if(stereo[0]) snprintf(d->nodes[node].stereotype, sizeof(d->nodes[node].stereotype), "<<%s>>", stereo);
if(url[0]) snprintf(d->nodes[node].link, sizeof(d->nodes[node].link), "%s", url);
const char *brace = strrchr(q, '{');
if(brace && (!lk || brace > strstr(lk, "]]"))) {
if(container) ix_push(ix, node);
else { body = node; body_depth = 0; section[0] = 0; }
}
continue;
}
// "A : +member"
char id[64];
const char *q = ix_read_name(p, id, sizeof(id));
q = ix_skip_ws(q);
if(id[0] && *q == ':') {
s32 node = ix_node(ix, id, NULL, NODE_CLASS, false);
if(node >= 0) ix_member(d, node, q + 1, NULL);
}
}
ix_finish(ix, false);
}
internal b32 diagram_import_plantuml(Diagram *d, String8 text)
{
ScratchArena scratch = ScratchGet();
IxLines lines;
ix_split_lines(scratch.arena, text, &lines, false);
diagram_clear(d);
Importer ix = {};
ix.d = d;
ix.map = PushArray(scratch.arena, IxEntry, DIAGRAM_MAX_NODES);
snprintf(d->title, sizeof(d->title), "Imported diagram");
// NOTE: only the first @startuml ... @enduml block
u32 start = 0, end = lines.count;
for(u32 i = 0; i < lines.count; ++i) {
if(!strncmp(lines.line[i], "@startuml", 9)) start = i + 1;
else if(!strncmp(lines.line[i], "@enduml", 7)) { end = i; break; }
}
IxLines body = {lines.line + start, end > start ? end - start : 0};
if(puml_is_sequence(&body)) puml_import_sequence(&ix, &body, scratch.arena);
else puml_import_class(&ix, &body);
scratch_end(&scratch);
return d->live_nodes > 0;
}
//- format detection
typedef enum TextFormat {
TEXT_FORMAT_UNKNOWN,
TEXT_FORMAT_DIT,
TEXT_FORMAT_MERMAID,
TEXT_FORMAT_PLANTUML,
} TextFormat;
internal TextFormat diagram_detect_format(String8 text, const char *name_hint)
{
if(name_hint) {
u64 n = strlen(name_hint);
const char *ext = strrchr(name_hint, '.');
if(ext && (!strcasecmp(ext, ".mmd") || !strcasecmp(ext, ".mermaid"))) return TEXT_FORMAT_MERMAID;
if(ext && (!strcasecmp(ext, ".puml") || !strcasecmp(ext, ".plantuml") || !strcasecmp(ext, ".pu") || !strcasecmp(ext, ".iuml") || !strcasecmp(ext, ".wsd"))) return TEXT_FORMAT_PLANTUML;
if(n > 8 && !strcasecmp(name_hint + n - 8, ".dit.txt")) return TEXT_FORMAT_DIT;
}
// first meaningful line
const char *at = (const char *)text.data, *end = at + text.size;
b32 front_matter = false;
while(at < end) {
const char *ls = at;
while(at < end && *at != '\n') ++at;
char line[128];
u64 len = Min((u64)(at - ls), (u64)sizeof(line) - 1);
MemCpy(line, ls, len);
line[len] = 0;
if(at < end) ++at;
ix_trim(line);
if(!line[0] || !strncmp(line, "%%", 2) || !strncmp(line, "```", 3) || line[0] == '\'') continue;
if(!strcmp(line, "---")) { front_matter = !front_matter; continue; }
if(front_matter) continue;
if(line[0] == '#' || !strncmp(line, "//", 2)) {
if(strstr(line, "design-it")) return TEXT_FORMAT_DIT;
continue;
}
if(!strncmp(line, "@start", 6)) return TEXT_FORMAT_PLANTUML;
const char *mm[] = {"classDiagram", "sequenceDiagram", "flowchart", "graph", "stateDiagram", "erDiagram"};
for(u32 i = 0; i < ArrayCount(mm); ++i) if(!strncmp(line, mm[i], strlen(mm[i]))) return TEXT_FORMAT_MERMAID;
if(!strncmp(line, "diagram ", 8)) return TEXT_FORMAT_DIT;
char word[32];
dsl_read_quoted(line, word, sizeof(word));
if(dsl_match_node_kind(word) >= 0) return TEXT_FORMAT_DIT;
return TEXT_FORMAT_UNKNOWN;
}
return TEXT_FORMAT_UNKNOWN;
}
// NOTE: any text format into d (cleared): .dit.txt DSL, mermaid, plantuml
internal b32 diagram_import_text(Diagram *d, String8 text, const char *name_hint)
{
switch(diagram_detect_format(text, name_hint)) {
case TEXT_FORMAT_MERMAID: return diagram_import_mermaid(d, text);
case TEXT_FORMAT_PLANTUML: return diagram_import_plantuml(d, text);
case TEXT_FORMAT_DIT: return diagram_from_dsl(d, text);
default: return diagram_from_dsl(d, text);
}
}
//- export
internal void ix_emit_id(StrBuf *b, const char *key)
{
// keys are already [a-z0-9_], but a leading digit trips both tools up
if(key[0] >= '0' && key[0] <= '9') strbuf_fmt(b, "n_");
strbuf_fmt(b, "%s", key);
}
internal void ix_emit_text(StrBuf *b, const char *s, b32 mermaid)
{
for(; *s; ++s) {
if(*s == '"') strbuf_fmt(b, mermaid ? "#quot;" : "'");
else if(*s == '\n') strbuf_fmt(b, mermaid ? "
" : "\\n");
else strbuf_fmt(b, "%c", *s);
}
}
// NOTE: doc text as comment lines (%% / ') so it survives a round trip through the file
internal void ix_emit_doc_comment(StrBuf *b, Diagram *d, u32 off, u32 len, const char *prefix, const char *indent)
{
String8 doc = diagram_doc(d, off, len);
if(!doc.size) return;
u64 start = 0;
for(u64 i = 0; i <= doc.size; ++i) {
if(i < doc.size && doc.data[i] != '\n') continue;
strbuf_fmt(b, "%s%s %.*s\n", indent, prefix, (int)(i - start), (char *)doc.data + start);
start = i + 1;
}
}
internal void ix_sequence_order(Diagram *d, Arena *arena, s32 **out_lines, u32 *out_line_count, s32 **out_msgs, u32 *out_msg_count)
{
s32 *lines = PushArray(arena, s32, d->node_count + 1);
s32 *msgs = PushArray(arena, s32, d->edge_count + 1);
u32 nl = 0, nm = 0;
for(u32 i = 0; i < d->node_count; ++i) if(d->nodes[i].alive && node_kind_is_lifeline(d->nodes[i].kind)) lines[nl++] = (s32)i;
for(u32 a = 1; a < nl; ++a) { s32 k = lines[a], j = (s32)a - 1; while(j >= 0 && d->nodes[lines[j]].x > d->nodes[k].x) { lines[j + 1] = lines[j]; --j; } lines[j + 1] = k; }
for(u32 e = 0; e < d->edge_count; ++e) if(d->edges[e].alive && diagram_edge_is_message(d, (s32)e)) msgs[nm++] = (s32)e;
for(u32 a = 1; a < nm; ++a) { s32 k = msgs[a], j = (s32)a - 1; while(j >= 0 && d->edges[msgs[j]].msg_y > d->edges[k].msg_y) { msgs[j + 1] = msgs[j]; --j; } msgs[j + 1] = k; }
*out_lines = lines; *out_line_count = nl; *out_msgs = msgs; *out_msg_count = nm;
}
typedef enum MermaidStyle {
MERMAID_AUTO,
MERMAID_CLASS,
MERMAID_FLOWCHART,
MERMAID_SEQUENCE,
} MermaidStyle;
internal b32 diagram_has_lifelines(Diagram *d)
{
for(u32 i = 0; i < d->node_count; ++i) if(d->nodes[i].alive && node_kind_is_lifeline(d->nodes[i].kind)) return true;
return false;
}
internal void mm_emit_flow_nodes(StrBuf *b, Diagram *d, s32 parent, u32 depth)
{
for(u32 i = 0; i < d->node_count; ++i) {
DiagramNode *n = &d->nodes[i];
if(!n->alive || n->parent != parent || node_kind_is_lifeline(n->kind)) continue;
for(u32 k = 0; k < depth + 1; ++k) strbuf_fmt(b, " ");
if(n->kind == NODE_MODULE) {
strbuf_fmt(b, "subgraph ");
ix_emit_id(b, n->key);
strbuf_fmt(b, " [\"");
ix_emit_text(b, n->name, true);
strbuf_fmt(b, "\"]\n");
mm_emit_flow_nodes(b, d, (s32)i, depth + 1);
for(u32 k = 0; k < depth + 1; ++k) strbuf_fmt(b, " ");
strbuf_fmt(b, "end\n");
continue;
}
const char *open = "[\"", *close = "\"]";
if(n->kind == NODE_STORAGE) { open = "[(\""; close = "\")]"; }
if(n->kind == NODE_STATE) { open = "([\""; close = "\"])"; }
if(n->kind == NODE_NOTE) { open = ">\""; close = "\"]"; }
if(n->kind == NODE_INTERFACE) { open = "[/\""; close = "\"/]"; }
if(n->kind == NODE_STATE && !strcmp(n->stereotype, "decision")) { open = "{\""; close = "\"}"; }
ix_emit_id(b, n->key);
strbuf_fmt(b, "%s", open);
ix_emit_text(b, n->name, true);
if(n->stereotype[0] && strcmp(n->stereotype, "decision")) { strbuf_fmt(b, "
"); ix_emit_text(b, n->stereotype, true); strbuf_fmt(b, ""); }
strbuf_fmt(b, "%s\n", close);
}
}
internal String8 diagram_export_mermaid(Arena *arena, Diagram *d, MermaidStyle style)
{
StrBuf b;
strbuf_init(arena, &b, MiB(2) + (u64)d->text_size * 2);
if(style == MERMAID_AUTO) {
b32 sections = false;
for(u32 i = 0; i < d->node_count; ++i) if(d->nodes[i].alive && d->nodes[i].first_section >= 0) sections = true;
style = diagram_has_lifelines(d) ? MERMAID_SEQUENCE : (sections ? MERMAID_CLASS : MERMAID_FLOWCHART);
}
strbuf_fmt(&b, "---\ntitle: %s\n---\n", d->title);
ix_emit_doc_comment(&b, d, d->doc_off, d->doc_len, "%%", "");
if(style == MERMAID_SEQUENCE) {
strbuf_fmt(&b, "sequenceDiagram\n");
s32 *lines, *msgs;
u32 nl, nm;
ix_sequence_order(d, arena, &lines, &nl, &msgs, &nm);
for(u32 i = 0; i < nl; ++i) {
DiagramNode *n = &d->nodes[lines[i]];
strbuf_fmt(&b, " %s ", n->kind == NODE_ACTOR ? "actor" : "participant");
ix_emit_id(&b, n->key);
strbuf_fmt(&b, " as ");
ix_emit_text(&b, n->name, true);
strbuf_fmt(&b, "\n");
}
for(u32 i = 0; i < nm; ++i) {
DiagramEdge *e = &d->edges[msgs[i]];
const char *op = "->>";
if(e->kind == EDGE_REPLY) op = "-->>";
else if(e->kind == EDGE_ASYNC) op = "-)";
else if(e->kind == EDGE_DEPENDENCY) op = "-->";
strbuf_fmt(&b, " ");
ix_emit_id(&b, d->nodes[e->src].key);
strbuf_fmt(&b, "%s", op);
ix_emit_id(&b, d->nodes[e->dst].key);
strbuf_fmt(&b, ": ");
ix_emit_text(&b, e->label, true);
strbuf_fmt(&b, "\n");
}
return ToString8Size((u8 *)b.data, b.size);
}
if(style == MERMAID_FLOWCHART) {
strbuf_fmt(&b, "flowchart TD\n");
mm_emit_flow_nodes(&b, d, -1, 0);
for(u32 i = 0; i < d->edge_count; ++i) {
DiagramEdge *e = &d->edges[i];
if(!e->alive || diagram_edge_is_message(d, (s32)i)) continue;
const char *op = "-->";
switch(e->kind) {
case EDGE_DEPENDENCY: case EDGE_IMPLEMENTS: case EDGE_ASYNC: case EDGE_REPLY: op = "-.->"; break;
case EDGE_DATAFLOW: op = "==>"; break;
case EDGE_BIDIR: op = "<-->"; break;
case EDGE_LINK: op = "---"; break;
}
strbuf_fmt(&b, " ");
ix_emit_id(&b, d->nodes[e->src].key);
strbuf_fmt(&b, " %s", op);
if(e->label[0]) { strbuf_fmt(&b, "|\""); ix_emit_text(&b, e->label, true); strbuf_fmt(&b, "\"|"); }
strbuf_fmt(&b, " ");
ix_emit_id(&b, d->nodes[e->dst].key);
strbuf_fmt(&b, "\n");
}
for(u32 i = 0; i < d->node_count; ++i) {
DiagramNode *n = &d->nodes[i];
char url[1024];
if(!n->alive || !n->link[0] || !diagram_link_url(d, n->link, url, sizeof(url))) continue;
strbuf_fmt(&b, " click ");
ix_emit_id(&b, n->key);
strbuf_fmt(&b, " href \"%s\" _blank\n", url);
}
return ToString8Size((u8 *)b.data, b.size);
}
strbuf_fmt(&b, "classDiagram\n");
// NOTE: mermaid namespaces don't nest: every node goes into its nearest module's namespace
for(u32 pass = 0; pass < 2; ++pass) {
for(u32 m = 0; m < d->node_count; ++m) {
DiagramNode *mod = &d->nodes[m];
b32 is_ns = (pass == 1 && mod->alive && mod->kind == NODE_MODULE);
if(pass == 1 && !is_ns) continue;
if(pass == 0 && m > 0) break;
b32 any = false;
for(u32 i = 0; i < d->node_count; ++i) {
DiagramNode *n = &d->nodes[i];
if(!n->alive || n->kind == NODE_MODULE || node_kind_is_lifeline(n->kind)) continue;
s32 home = n->parent;
while(home >= 0 && d->nodes[home].kind != NODE_MODULE) home = d->nodes[home].parent;
if(pass == 0 ? home >= 0 : home != (s32)m) continue;
const char *indent = (pass == 1) ? " " : " ";
if(pass == 1 && !any) {
strbuf_fmt(&b, " namespace ");
ix_emit_id(&b, mod->key);
strbuf_fmt(&b, " {\n");
}
any = true;
ix_emit_doc_comment(&b, d, n->doc_off, n->doc_len, "%%", indent);
if(n->kind == NODE_NOTE) continue; // notes go out as `note` lines below
strbuf_fmt(&b, "%sclass ", indent);
ix_emit_id(&b, n->key);
strbuf_fmt(&b, "[\"");
ix_emit_text(&b, n->name, true);
strbuf_fmt(&b, "\"] {\n");
const char *st = NULL;
if(n->kind == NODE_INTERFACE) st = "interface";
else if(n->kind == NODE_ENUM) st = "enumeration";
if(n->stereotype[0] == '<') strbuf_fmt(&b, "%s %s\n", indent, n->stereotype);
else if(st) strbuf_fmt(&b, "%s <<%s>>\n", indent, st);
else if(n->stereotype[0]) { strbuf_fmt(&b, "%s <<", indent); ix_emit_text(&b, n->stereotype, true); strbuf_fmt(&b, ">>\n"); }
for(s32 s = n->first_section; s >= 0; s = d->sections[s].next) {
for(s32 mi = d->sections[s].first_member; mi >= 0; mi = d->members[mi].next) {
NodeMember *mem = &d->members[mi];
char vis = (mem->visibility == '+' || mem->visibility == '-' || mem->visibility == '#' || mem->visibility == '~') ? mem->visibility : 0;
// NOTE: mermaid writes generics as List~int~, a bare < breaks its parser
char name[64], type[80];
snprintf(name, sizeof(name), "%s", mem->name);
snprintf(type, sizeof(type), "%s", mem->type);
for(char *c = name; *c; ++c) if(*c == '<' || *c == '>') *c = '~';
for(char *c = type; *c; ++c) if(*c == '<' || *c == '>') *c = '~';
strbuf_fmt(&b, "%s ", indent);
if(vis) strbuf_fmt(&b, "%c", vis);
if(strchr(name, '(')) strbuf_fmt(&b, "%s%s%s\n", name, type[0] ? " " : "", type);
else if(type[0]) strbuf_fmt(&b, "%s %s\n", type, name);
else strbuf_fmt(&b, "%s\n", name);
}
}
strbuf_fmt(&b, "%s}\n", indent);
}
if(pass == 1 && any) strbuf_fmt(&b, " }\n");
}
}
for(u32 i = 0; i < d->edge_count; ++i) {
DiagramEdge *e = &d->edges[i];
if(!e->alive) continue;
DiagramNode *a = &d->nodes[e->src], *c = &d->nodes[e->dst];
if(a->kind == NODE_MODULE || c->kind == NODE_MODULE || a->kind == NODE_NOTE || c->kind == NODE_NOTE) continue;
const char *op = "-->";
switch(e->kind) {
case EDGE_INHERITANCE: op = "--|>"; break;
case EDGE_IMPLEMENTS: op = "..|>"; break;
case EDGE_COMPOSITION: op = "*--"; break;
case EDGE_AGGREGATION: op = "o--"; break;
case EDGE_DEPENDENCY: case EDGE_ASYNC: case EDGE_REPLY: op = "..>"; break;
case EDGE_BIDIR: op = "<-->"; break;
case EDGE_LINK: op = "--"; break;
}
strbuf_fmt(&b, " ");
ix_emit_id(&b, a->key);
if(e->src_mult[0]) strbuf_fmt(&b, " \"%s\"", e->src_mult);
strbuf_fmt(&b, " %s ", op);
if(e->dst_mult[0]) strbuf_fmt(&b, "\"%s\" ", e->dst_mult);
ix_emit_id(&b, c->key);
if(e->label[0]) { strbuf_fmt(&b, " : "); ix_emit_text(&b, e->label, true); }
strbuf_fmt(&b, "\n");
}
for(u32 i = 0; i < d->node_count; ++i) {
DiagramNode *n = &d->nodes[i];
if(!n->alive || n->kind != NODE_NOTE) continue;
// a note linked to one class becomes "note for", otherwise a free note
s32 target = -1;
for(u32 e = 0; e < d->edge_count && target < 0; ++e) {
DiagramEdge *ed = &d->edges[e];
if(!ed->alive) continue;
if(ed->src == (s32)i && d->nodes[ed->dst].kind != NODE_MODULE) target = ed->dst;
else if(ed->dst == (s32)i && d->nodes[ed->src].kind != NODE_MODULE) target = ed->src;
}
strbuf_fmt(&b, " note ");
if(target >= 0) { strbuf_fmt(&b, "for "); ix_emit_id(&b, d->nodes[target].key); strbuf_fmt(&b, " "); }
strbuf_fmt(&b, "\"");
ix_emit_text(&b, n->note[0] ? n->note : n->name, true);
strbuf_fmt(&b, "\"\n");
}
for(u32 i = 0; i < d->node_count; ++i) {
DiagramNode *n = &d->nodes[i];
char url[1024];
if(!n->alive || n->kind == NODE_MODULE || n->kind == NODE_NOTE || !n->link[0] || !diagram_link_url(d, n->link, url, sizeof(url))) continue;
strbuf_fmt(&b, " click ");
ix_emit_id(&b, n->key);
strbuf_fmt(&b, " href \"%s\" \"%s\"\n", url, n->link);
}
return ToString8Size((u8 *)b.data, b.size);
}
internal void puml_emit_nodes(StrBuf *b, Diagram *d, s32 parent, u32 depth)
{
for(u32 i = 0; i < d->node_count; ++i) {
DiagramNode *n = &d->nodes[i];
if(!n->alive || n->parent != parent || node_kind_is_lifeline(n->kind)) continue;
char indent[32] = {};
for(u32 k = 0; k < depth && k < 7; ++k) strcat(indent, " ");
ix_emit_doc_comment(b, d, n->doc_off, n->doc_len, "'", indent);
if(n->kind == NODE_MODULE) {
strbuf_fmt(b, "%spackage \"", indent);
ix_emit_text(b, n->name, false);
strbuf_fmt(b, "\" as ");
ix_emit_id(b, n->key);
strbuf_fmt(b, " {\n");
puml_emit_nodes(b, d, (s32)i, depth + 1);
strbuf_fmt(b, "%s}\n", indent);
continue;
}
if(n->kind == NODE_NOTE) {
strbuf_fmt(b, "%snote \"", indent);
ix_emit_text(b, n->note[0] ? n->note : n->name, false);
strbuf_fmt(b, "\" as ");
ix_emit_id(b, n->key);
strbuf_fmt(b, "\n");
continue;
}
const char *word = "class";
const char *st = NULL;
switch(n->kind) {
case NODE_INTERFACE: word = "interface"; break;
case NODE_ENUM: word = "enum"; break;
case NODE_STRUCT: st = "struct"; break;
case NODE_SYSTEM: st = "system"; break;
case NODE_STORAGE: if(n->first_section >= 0) st = "storage"; else word = "database"; break; // database can't hold members
case NODE_STATE: st = "state"; break;
}
strbuf_fmt(b, "%s%s \"", indent, word);
ix_emit_text(b, n->name, false);
strbuf_fmt(b, "\" as ");
ix_emit_id(b, n->key);
if(n->stereotype[0] == '<') strbuf_fmt(b, " %s", n->stereotype);
else if(n->stereotype[0]) { strbuf_fmt(b, " <<"); ix_emit_text(b, n->stereotype, false); strbuf_fmt(b, ">>"); }
else if(st) strbuf_fmt(b, " <<%s>>", st);
char url[1024];
if(n->link[0] && diagram_link_url(d, n->link, url, sizeof(url))) strbuf_fmt(b, " [[%s %s]]", url, n->link);
if(n->first_section < 0) { strbuf_fmt(b, "\n"); continue; }
strbuf_fmt(b, " {\n");
b32 first_section = true;
for(s32 s = n->first_section; s >= 0; s = d->sections[s].next) {
NodeSection *sec = &d->sections[s];
if(!first_section || (strcmp(sec->title, "fields") && strcmp(sec->title, "methods") && strcmp(sec->title, "values"))) strbuf_fmt(b, "%s -- %s --\n", indent, sec->title);
first_section = false;
for(s32 mi = sec->first_member; mi >= 0; mi = d->members[mi].next) {
NodeMember *mem = &d->members[mi];
char vis = (mem->visibility == '+' || mem->visibility == '-' || mem->visibility == '#' || mem->visibility == '~') ? mem->visibility : 0;
strbuf_fmt(b, "%s ", indent);
if(vis) strbuf_fmt(b, "%c", vis);
strbuf_fmt(b, "%s", mem->name);
if(mem->type[0]) strbuf_fmt(b, " : %s", mem->type);
strbuf_fmt(b, "\n");
}
}
strbuf_fmt(b, "%s}\n", indent);
}
}
internal String8 diagram_export_plantuml(Arena *arena, Diagram *d)
{
StrBuf b;
strbuf_init(arena, &b, MiB(2) + (u64)d->text_size * 2);
strbuf_fmt(&b, "@startuml\ntitle %s\n", d->title);
ix_emit_doc_comment(&b, d, d->doc_off, d->doc_len, "'", "");
if(diagram_has_lifelines(d)) {
s32 *lines, *msgs;
u32 nl, nm;
ix_sequence_order(d, arena, &lines, &nl, &msgs, &nm);
for(u32 i = 0; i < nl; ++i) {
DiagramNode *n = &d->nodes[i < nl ? lines[i] : 0];
strbuf_fmt(&b, "%s \"", n->kind == NODE_ACTOR ? "actor" : "participant");
ix_emit_text(&b, n->name, false);
strbuf_fmt(&b, "\" as ");
ix_emit_id(&b, n->key);
strbuf_fmt(&b, "\n");
}
for(u32 i = 0; i < nm; ++i) {
DiagramEdge *e = &d->edges[msgs[i]];
const char *op = "->";
if(e->kind == EDGE_REPLY || e->kind == EDGE_DEPENDENCY) op = "-->";
else if(e->kind == EDGE_ASYNC) op = "->>";
ix_emit_id(&b, d->nodes[e->src].key);
strbuf_fmt(&b, " %s ", op);
ix_emit_id(&b, d->nodes[e->dst].key);
if(e->label[0]) { strbuf_fmt(&b, " : "); ix_emit_text(&b, e->label, false); }
strbuf_fmt(&b, "\n");
}
strbuf_fmt(&b, "@enduml\n");
return ToString8Size((u8 *)b.data, b.size);
}
strbuf_fmt(&b, "allowmixing\n\n");
puml_emit_nodes(&b, d, -1, 0);
strbuf_fmt(&b, "\n");
for(u32 i = 0; i < d->edge_count; ++i) {
DiagramEdge *e = &d->edges[i];
if(!e->alive) continue;
const char *op = "-->";
switch(e->kind) {
case EDGE_INHERITANCE: op = "--|>"; break;
case EDGE_IMPLEMENTS: op = "..|>"; break;
case EDGE_COMPOSITION: op = "*--"; break;
case EDGE_AGGREGATION: op = "o--"; break;
case EDGE_DEPENDENCY: case EDGE_REPLY: op = "..>"; break;
case EDGE_ASYNC: op = "..>"; break;
case EDGE_DATAFLOW: op = "-[bold]->"; break;
case EDGE_BIDIR: op = "<-->"; break;
case EDGE_LINK: op = "--"; break;
}
ix_emit_id(&b, d->nodes[e->src].key);
if(e->src_mult[0]) strbuf_fmt(&b, " \"%s\"", e->src_mult);
strbuf_fmt(&b, " %s ", op);
if(e->dst_mult[0]) strbuf_fmt(&b, "\"%s\" ", e->dst_mult);
ix_emit_id(&b, d->nodes[e->dst].key);
if(e->label[0]) { strbuf_fmt(&b, " : "); ix_emit_text(&b, e->label, false); }
strbuf_fmt(&b, "\n");
ix_emit_doc_comment(&b, d, e->doc_off, e->doc_len, "'", " ");
}
strbuf_fmt(&b, "@enduml\n");
return ToString8Size((u8 *)b.data, b.size);
}
internal b32 write_text_file(const char *path, String8 text)
{
FILE *f = fopen(path, "wb");
if(!f) return false;
b32 ok = fwrite(text.data, 1, text.size, f) == text.size;
fclose(f);
return ok;
}
internal b32 path_has_extension(const char *path, const char *ext)
{
u64 pl = strlen(path), el = strlen(ext);
return pl >= el && !strcasecmp(path + pl - el, ext);
}
// NOTE: every text / vector export by file extension (png needs the renderer, see the app)
internal b32 diagram_export_by_extension(Diagram *d, const char *path, const char *style, const u32 *colors, char *message, u32 cap)
{
ScratchArena scratch = ScratchGet();
b32 ok = false;
const char *what = "";
if(path_has_extension(path, ".svg")) {
ok = diagram_export_svg(d, path, colors);
what = "SVG";
} else if(path_has_extension(path, ".mmd") || path_has_extension(path, ".mermaid") || path_has_extension(path, ".md")) {
MermaidStyle ms = MERMAID_AUTO;
if(style && !strncasecmp(style, "class", 5)) ms = MERMAID_CLASS;
else if(style && (!strncasecmp(style, "flow", 4) || !strcasecmp(style, "graph"))) ms = MERMAID_FLOWCHART;
else if(style && !strncasecmp(style, "seq", 3)) ms = MERMAID_SEQUENCE;
String8 text = diagram_export_mermaid(scratch.arena, d, ms);
if(path_has_extension(path, ".md")) {
// markdown: a fenced block github / gitlab render
StrBuf b;
strbuf_init(scratch.arena, &b, text.size + 64);
strbuf_fmt(&b, "```mermaid\n%.*s```\n", (int)text.size, (char *)text.data);
text = ToString8Size((u8 *)b.data, b.size);
}
ok = write_text_file(path, text);
what = "Mermaid";
} else if(path_has_extension(path, ".puml") || path_has_extension(path, ".plantuml") || path_has_extension(path, ".pu") || path_has_extension(path, ".wsd")) {
ok = write_text_file(path, diagram_export_plantuml(scratch.arena, d));
what = "PlantUML";
} else if(path_has_extension(path, ".dit")) {
char keep[512];
snprintf(keep, sizeof(keep), "%s", d->file_path);
b32 dirty = d->dirty;
ok = diagram_save_binary(d, path);
snprintf(d->file_path, sizeof(d->file_path), "%s", keep);
d->dirty = dirty;
what = "binary .dit";
} else {
ok = write_text_file(path, diagram_to_dsl(scratch.arena, d));
what = "DSL";
}
snprintf(message, cap, ok ? "exported %s -> %s (%u nodes, %u edges)" : "failed to export %s -> %s", what, path, d->live_nodes, d->live_edges);
scratch_end(&scratch);
return ok;
}