From 2b0f2d394fdfcc0320d03dd2acc738bee74aaa0e Mon Sep 17 00:00:00 2001 From: Alexander Wang Date: Sat, 3 Dec 2022 00:06:59 -0800 Subject: [PATCH] add check for sequence diagram connection error --- d2compiler/compile_test.go | 12 ++++++++++++ d2graph/d2graph.go | 14 ++++++++++++++ .../d2compiler/TestCompile/leaky_sequence.exp.json | 12 ++++++++++++ 3 files changed, 38 insertions(+) create mode 100644 testdata/d2compiler/TestCompile/leaky_sequence.exp.json diff --git a/d2compiler/compile_test.go b/d2compiler/compile_test.go index 35524f803..d4f979532 100644 --- a/d2compiler/compile_test.go +++ b/d2compiler/compile_test.go @@ -1520,6 +1520,18 @@ dst.id <-> src.dst_id assert.String(t, "sequence_diagram", g.Root.Attributes.Shape.Value) }, }, + { + name: "leaky_sequence", + + text: `x: { + shape: sequence_diagram + a +} +b -> x.a +`, + expErr: `d2/testdata/d2compiler/TestCompile/leaky_sequence.d2:5:1: connections within sequence diagrams can connect only to other objects within the same sequence diagram +`, + }, { name: "root_direction", diff --git a/d2graph/d2graph.go b/d2graph/d2graph.go index c6a00c507..961ab0bcb 100644 --- a/d2graph/d2graph.go +++ b/d2graph/d2graph.go @@ -711,6 +711,16 @@ func (e *Edge) AbsID() string { return fmt.Sprintf("%s(%s %s %s)[%d]", commonKey, strings.Join(srcIDA, "."), e.ArrowString(), strings.Join(dstIDA, "."), e.Index) } +func (obj *Object) outerSequenceDiagram() *Object { + for obj != nil { + obj = obj.Parent + if obj.IsSequenceDiagram() { + return obj + } + } + return nil +} + func (obj *Object) Connect(srcID, dstID []string, srcArrow, dstArrow bool, label string) (*Edge, error) { srcObj, srcID, err := ResolveUnderscoreKey(srcID, obj) if err != nil { @@ -732,6 +742,10 @@ func (obj *Object) Connect(srcID, dstID []string, srcArrow, dstArrow bool, label src := srcObj.EnsureChild(srcID) dst := dstObj.EnsureChild(dstID) + if src.outerSequenceDiagram() != dst.outerSequenceDiagram() { + return nil, errors.New("connections within sequence diagrams can connect only to other objects within the same sequence diagram") + } + edge := &Edge{ Attributes: Attributes{ Label: Scalar{ diff --git a/testdata/d2compiler/TestCompile/leaky_sequence.exp.json b/testdata/d2compiler/TestCompile/leaky_sequence.exp.json new file mode 100644 index 000000000..182b3c4e3 --- /dev/null +++ b/testdata/d2compiler/TestCompile/leaky_sequence.exp.json @@ -0,0 +1,12 @@ +{ + "graph": null, + "err": { + "ioerr": null, + "errs": [ + { + "range": "d2/testdata/d2compiler/TestCompile/leaky_sequence.d2,4:0:36-4:8:44", + "errmsg": "d2/testdata/d2compiler/TestCompile/leaky_sequence.d2:5:1: connections within sequence diagrams can only connect to other objects within the same sequence diagram" + } + ] + } +}