d2/d2ir/d2ir.go

777 lines
14 KiB
Go
Raw Normal View History

package d2ir
import (
2023-01-16 11:52:37 +00:00
"errors"
2023-01-11 19:05:50 +00:00
"fmt"
"strings"
2023-01-17 12:44:14 +00:00
"oss.terrastruct.com/util-go/go2"
"oss.terrastruct.com/d2/d2ast"
2023-01-11 23:50:49 +00:00
"oss.terrastruct.com/d2/d2format"
)
type Node interface {
node()
2023-01-18 01:39:31 +00:00
Copy(parent Node) Node
2023-01-17 12:44:14 +00:00
Parent() Node
2023-01-18 01:39:31 +00:00
ast() d2ast.Node
fmt.Stringer
}
2023-01-18 01:39:31 +00:00
var _ Node = &IR{}
var _ Node = &Scalar{}
var _ Node = &Field{}
var _ Node = &Edge{}
var _ Node = &Array{}
var _ Node = &Map{}
type Value interface {
Node
value()
}
var _ Value = &Scalar{}
var _ Value = &Array{}
var _ Value = &Map{}
type Composite interface {
Node
Value
composite()
}
var _ Composite = &Array{}
var _ Composite = &Map{}
2023-01-18 01:39:31 +00:00
func (n *IR) node() {}
func (n *Scalar) node() {}
func (n *Field) node() {}
func (n *Edge) node() {}
func (n *Array) node() {}
func (n *Map) node() {}
2023-01-18 01:39:31 +00:00
func (n *IR) Parent() Node { return n.parent }
2023-01-17 12:44:14 +00:00
func (n *Scalar) Parent() Node { return n.parent }
func (n *Field) Parent() Node { return n.parent }
func (n *Edge) Parent() Node { return n.parent }
func (n *Array) Parent() Node { return n.parent }
func (n *Map) Parent() Node { return n.parent }
func (n *Scalar) value() {}
func (n *Array) value() {}
func (n *Map) value() {}
2023-01-18 01:39:31 +00:00
func (n *IR) value() {}
func (n *Array) composite() {}
func (n *Map) composite() {}
2023-01-18 01:39:31 +00:00
func (n *IR) composite() {}
2023-01-18 01:39:31 +00:00
func (n *IR) String() string { return d2format.Format(n.ast()) }
func (n *Scalar) String() string { return d2format.Format(n.ast()) }
func (n *Field) String() string { return d2format.Format(n.ast()) }
func (n *Edge) String() string { return d2format.Format(n.ast()) }
func (n *Array) String() string { return d2format.Format(n.ast()) }
func (n *Map) String() string { return d2format.Format(n.ast()) }
2023-01-18 01:39:31 +00:00
type IR struct {
parent Node
AST *d2ast.Map `json:"ast"`
Map *Map `json:"base"`
}
func (ir *IR) Copy(newp Node) Node {
tmp := *ir
ir = &tmp
ir.parent = newp.(*IR)
ir.Map = ir.Map.Copy(ir).(*Map)
return ir
}
type Scalar struct {
2023-01-17 12:44:14 +00:00
parent Node
Value d2ast.Scalar `json:"value"`
}
2023-01-17 12:44:14 +00:00
func (s *Scalar) Copy(newp Node) Node {
tmp := *s
s = &tmp
s.parent = newp
return s
}
func (s *Scalar) Equal(s2 *Scalar) bool {
2023-01-11 23:50:49 +00:00
if _, ok := s.Value.(d2ast.String); ok {
if _, ok = s2.Value.(d2ast.String); ok {
return s.Value.ScalarString() == s2.Value.ScalarString()
}
}
return s.Value.Type() == s2.Value.Type() && s.Value.ScalarString() == s2.Value.ScalarString()
}
type Map struct {
2023-01-17 12:44:14 +00:00
parent Node
Fields []*Field `json:"fields"`
Edges []*Edge `json:"edges"`
}
2023-01-17 12:44:14 +00:00
func (m *Map) Copy(newp Node) Node {
tmp := *m
m = &tmp
m.parent = newp
m.Fields = append([]*Field(nil), m.Fields...)
for i := range m.Fields {
m.Fields[i] = m.Fields[i].Copy(m).(*Field)
}
m.Edges = append([]*Edge(nil), m.Edges...)
for i := range m.Edges {
m.Edges[i] = m.Edges[i].Copy(m).(*Edge)
}
return m
}
// Root reports whether the Map is the root of the D2 tree.
func (m *Map) Root() bool {
2023-01-18 01:39:31 +00:00
_, ok := m.parent.(*IR)
return ok
}
type Field struct {
parent *Map
Name string `json:"name"`
2023-01-11 19:05:50 +00:00
Primary *Scalar `json:"primary,omitempty"`
Composite Composite `json:"composite,omitempty"`
2023-01-17 12:44:14 +00:00
References []FieldReference `json:"references,omitempty"`
}
2023-01-17 12:44:14 +00:00
func (f *Field) Copy(newp Node) Node {
tmp := *f
f = &tmp
f.parent = newp.(*Map)
2023-01-17 12:44:14 +00:00
f.References = append([]FieldReference(nil), f.References...)
if f.Primary != nil {
f.Primary = f.Primary.Copy(f).(*Scalar)
}
if f.Composite != nil {
f.Composite = f.Composite.Copy(f).(Composite)
}
return f
}
type EdgeID struct {
SrcPath []string `json:"src_path"`
SrcArrow bool `json:"src_arrow"`
DstPath []string `json:"dst_path"`
DstArrow bool `json:"dst_arrow"`
2023-01-16 11:52:37 +00:00
// If nil, then any EdgeID with equal src/dst/arrows matches.
Index *int `json:"index"`
}
func NewEdgeIDs(k *d2ast.Key) (eida []*EdgeID) {
for _, ke := range k.Edges {
eida = append(eida, &EdgeID{
SrcPath: d2format.KeyPath(ke.Src),
SrcArrow: ke.SrcArrow == "<",
DstPath: d2format.KeyPath(ke.Dst),
DstArrow: ke.DstArrow == ">",
})
}
if k.EdgeIndex != nil && k.EdgeIndex.Int != nil {
eida[0].Index = k.EdgeIndex.Int
}
return eida
}
func (eid *EdgeID) Copy() *EdgeID {
tmp := *eid
eid = &tmp
eid.SrcPath = append([]string(nil), eid.SrcPath...)
eid.DstPath = append([]string(nil), eid.DstPath...)
return eid
}
2023-01-16 11:52:37 +00:00
func (eid *EdgeID) Match(eid2 *EdgeID) bool {
if eid.Index != nil && eid2.Index != nil {
if *eid.Index != *eid2.Index {
return false
}
}
if len(eid.SrcPath) != len(eid2.SrcPath) {
return false
}
if eid.SrcArrow != eid2.SrcArrow {
return false
}
for i, s := range eid.SrcPath {
if !strings.EqualFold(s, eid2.SrcPath[i]) {
return false
}
}
if len(eid.DstPath) != len(eid2.DstPath) {
return false
}
if eid.DstArrow != eid2.DstArrow {
return false
}
for i, s := range eid.DstPath {
if !strings.EqualFold(s, eid2.DstPath[i]) {
return false
}
}
return true
}
2023-01-17 12:44:14 +00:00
func (eid *EdgeID) resolveUnderscores(m *Map) (*EdgeID, *Map, error) {
eid = eid.Copy()
maxUnderscores := go2.Max(countUnderscores(eid.SrcPath), countUnderscores(eid.DstPath))
for i := 0; i < maxUnderscores; i++ {
if eid.SrcPath[0] == "_" {
eid.SrcPath = eid.SrcPath[1:]
} else {
2023-01-18 01:39:31 +00:00
mf := ParentField(m)
2023-01-17 12:44:14 +00:00
eid.SrcPath = append([]string{mf.Name}, eid.SrcPath...)
}
if eid.DstPath[0] == "_" {
eid.DstPath = eid.DstPath[1:]
} else {
2023-01-18 01:39:31 +00:00
mf := ParentField(m)
2023-01-17 12:44:14 +00:00
eid.DstPath = append([]string{mf.Name}, eid.DstPath...)
}
2023-01-18 01:39:31 +00:00
m = ParentMap(m)
2023-01-17 12:44:14 +00:00
if m == nil {
return nil, nil, errors.New("invalid underscore")
}
}
return eid, m, nil
}
func (eid *EdgeID) trimCommon() (common []string, _ *EdgeID) {
eid = eid.Copy()
for len(eid.SrcPath) > 1 && len(eid.DstPath) > 1 {
if !strings.EqualFold(eid.SrcPath[0], eid.DstPath[0]) {
return common, eid
}
common = append(common, eid.SrcPath[0])
eid.SrcPath = eid.SrcPath[1:]
eid.DstPath = eid.DstPath[1:]
}
return common, eid
}
type Edge struct {
parent *Map
ID *EdgeID `json:"edge_id"`
2023-01-11 19:05:50 +00:00
Primary *Scalar `json:"primary,omitempty"`
Map *Map `json:"map,omitempty"`
2023-01-16 15:45:13 +00:00
References []EdgeReference `json:"references,omitempty"`
}
2023-01-17 12:44:14 +00:00
func (e *Edge) Copy(newp Node) Node {
tmp := *e
e = &tmp
e.parent = newp.(*Map)
2023-01-16 15:45:13 +00:00
e.References = append([]EdgeReference(nil), e.References...)
if e.Primary != nil {
e.Primary = e.Primary.Copy(e).(*Scalar)
}
if e.Map != nil {
e.Map = e.Map.Copy(e).(*Map)
}
return e
}
type Array struct {
2023-01-17 12:44:14 +00:00
parent Node
Values []Value `json:"values"`
}
2023-01-17 12:44:14 +00:00
func (a *Array) Copy(newp Node) Node {
tmp := *a
a = &tmp
a.parent = newp
a.Values = append([]Value(nil), a.Values...)
for i := range a.Values {
a.Values[i] = a.Values[i].Copy(a).(Value)
}
return a
}
2023-01-17 12:44:14 +00:00
type FieldReference struct {
String *d2ast.StringBox `json:"string"`
KeyPath *d2ast.KeyPath `json:"key_path"`
2023-01-18 05:30:28 +00:00
Context *RefContext `json:"context"`
2023-01-16 15:45:13 +00:00
}
2023-01-17 12:44:14 +00:00
func (kr FieldReference) KeyPathIndex() int {
2023-01-16 15:45:13 +00:00
for i, sb := range kr.KeyPath.Path {
if sb == kr.String {
return i
}
}
panic("d2ir.KeyReference.KeyPathIndex: String not in KeyPath?")
}
2023-01-17 12:44:14 +00:00
func (kr FieldReference) EdgeDest() bool {
2023-01-16 15:45:13 +00:00
return kr.KeyPath == kr.Context.Edge.Dst
}
2023-01-17 12:44:14 +00:00
func (kr FieldReference) InEdge() bool {
2023-01-18 05:28:33 +00:00
return kr.Context.Edge != nil
}
type EdgeReference struct {
2023-01-18 05:30:28 +00:00
Context *RefContext `json:"context"`
}
type RefContext struct {
2023-01-18 05:30:28 +00:00
Key *d2ast.Key `json:"key"`
Edge *d2ast.Edge `json:"edge"`
Scope *d2ast.Map `json:"-"`
2023-01-18 01:39:31 +00:00
}
2023-01-16 15:45:13 +00:00
2023-01-18 05:28:33 +00:00
func (rc *RefContext) Copy() *RefContext {
tmp := *rc
return &tmp
}
2023-01-18 01:39:31 +00:00
// UnresolvedScopeMap is scope prior to interpreting _
// It does this by finding the referenced *Map of rc.Scope
func (rc *RefContext) UnresolvedScopeMap(m *Map) *Map {
for {
fm := ParentField(m)
if fm == nil {
return m
}
for _, ref := range fm.References {
if ref.KeyPath != ref.Context.Key.Key {
continue
}
if ref.Context.Key.Value.Unbox() == rc.Scope {
return m
}
}
m = ParentMap(m)
}
2023-01-16 15:45:13 +00:00
}
2023-01-18 01:39:31 +00:00
func (rc *RefContext) EdgeIndex() int {
2023-01-17 11:05:56 +00:00
for i, e := range rc.Key.Edges {
if e == rc.Edge {
2023-01-16 15:45:13 +00:00
return i
}
}
panic("d2ir.RefContext.EdgeIndex: Edge not in Key.Edges?")
}
2023-01-16 11:52:37 +00:00
func (m *Map) FieldCountRecursive() int {
if m == nil {
return 0
}
acc := len(m.Fields)
for _, f := range m.Fields {
2023-01-18 01:47:47 +00:00
f_m := ToMap(f)
if f_m != nil {
2023-01-16 11:52:37 +00:00
acc += f_m.FieldCountRecursive()
}
}
for _, e := range m.Edges {
if e.Map != nil {
acc += e.Map.FieldCountRecursive()
}
}
return acc
}
2023-01-16 11:52:37 +00:00
func (m *Map) EdgeCountRecursive() int {
if m == nil {
return 0
}
acc := len(m.Edges)
2023-01-17 12:44:14 +00:00
for _, f := range m.Fields {
2023-01-18 01:47:47 +00:00
f_m := ToMap(f)
if f_m != nil {
2023-01-17 12:44:14 +00:00
acc += f_m.EdgeCountRecursive()
}
}
for _, e := range m.Edges {
if e.Map != nil {
2023-01-16 11:52:37 +00:00
acc += e.Map.EdgeCountRecursive()
}
}
return acc
}
2023-01-17 12:44:14 +00:00
func (m *Map) GetField(ida []string) *Field {
for len(ida) > 0 && ida[0] == "_" {
2023-01-18 01:39:31 +00:00
m = ParentMap(m)
2023-01-17 12:44:14 +00:00
if m == nil {
return nil
}
}
return m.getField(ida)
}
func (m *Map) getField(ida []string) *Field {
if len(ida) == 0 {
2023-01-16 11:52:37 +00:00
return nil
}
s := ida[0]
rest := ida[1:]
2023-01-17 12:44:14 +00:00
if s == "_" {
return nil
}
for _, f := range m.Fields {
if !strings.EqualFold(f.Name, s) {
continue
}
if len(rest) == 0 {
2023-01-16 11:52:37 +00:00
return f
}
2023-01-18 01:47:47 +00:00
f_m := ToMap(f)
if f_m != nil {
2023-01-17 12:44:14 +00:00
return f_m.getField(rest)
}
}
2023-01-16 11:52:37 +00:00
return nil
}
2023-01-17 12:44:14 +00:00
func (m *Map) EnsureField(ida []string) (*Field, error) {
for len(ida) > 0 && ida[0] == "_" {
2023-01-18 01:39:31 +00:00
m = ParentMap(m)
2023-01-17 12:44:14 +00:00
if m == nil {
return nil, errors.New("invalid underscore")
}
ida = ida[1:]
}
return m.ensureField(ida)
}
func (m *Map) ensureField(ida []string) (*Field, error) {
if len(ida) == 0 {
2023-01-17 12:44:14 +00:00
return nil, errors.New("invalid underscore")
}
s := ida[0]
rest := ida[1:]
2023-01-17 12:44:14 +00:00
if s == "_" {
return nil, errors.New(`parent "_" can only be used in the beginning of paths, e.g. "_.x"`)
}
for _, f := range m.Fields {
if !strings.EqualFold(f.Name, s) {
continue
}
if len(rest) == 0 {
2023-01-16 11:52:37 +00:00
return f, nil
}
2023-01-18 01:47:47 +00:00
if _, ok := f.Composite.(*Array); ok {
2023-01-16 11:52:37 +00:00
return nil, errors.New("cannot index into array")
}
2023-01-18 01:47:47 +00:00
f_m := ToMap(f)
if f_m == nil {
f_m = &Map{
parent: f,
}
f.Composite = f_m
}
2023-01-18 01:47:47 +00:00
return f_m.ensureField(rest)
}
f := &Field{
parent: m,
Name: s,
}
m.Fields = append(m.Fields, f)
if len(rest) == 0 {
2023-01-16 11:52:37 +00:00
return f, nil
}
2023-01-18 01:47:47 +00:00
f_m := &Map{
parent: f,
}
2023-01-18 01:47:47 +00:00
f.Composite = f_m
return f_m.ensureField(rest)
}
2023-01-18 01:39:31 +00:00
func (m *Map) DeleteField(ida []string) bool {
if len(ida) == 0 {
return false
}
s := ida[0]
rest := ida[1:]
for i, f := range m.Fields {
if !strings.EqualFold(f.Name, s) {
continue
}
if len(rest) == 0 {
copy(m.Fields[i:], m.Fields[i+1:])
return true
}
2023-01-18 01:47:47 +00:00
f_m := ToMap(f)
if f_m != nil {
2023-01-18 01:39:31 +00:00
return f_m.DeleteField(rest)
}
}
return false
}
2023-01-16 11:52:37 +00:00
func (m *Map) GetEdges(eid *EdgeID) []*Edge {
2023-01-17 12:44:14 +00:00
eid, m, err := eid.resolveUnderscores(m)
if err != nil {
return nil
}
common, eid := eid.trimCommon()
if len(common) > 0 {
2023-01-17 12:44:14 +00:00
f := m.GetField(common)
2023-01-16 11:52:37 +00:00
if f == nil {
return nil
}
2023-01-18 01:47:47 +00:00
f_m := ToMap(f)
if f_m != nil {
2023-01-16 11:52:37 +00:00
return f_m.GetEdges(eid)
}
2023-01-16 11:52:37 +00:00
return nil
}
2023-01-16 11:52:37 +00:00
var ea []*Edge
for _, e := range m.Edges {
2023-01-16 11:52:37 +00:00
if e.ID.Match(eid) {
ea = append(ea, e)
}
}
return ea
}
func (m *Map) EnsureEdge(eid *EdgeID) (*Edge, error) {
2023-01-17 12:44:14 +00:00
eid, m, err := eid.resolveUnderscores(m)
if err != nil {
return nil, err
}
2023-01-16 11:52:37 +00:00
common, eid := eid.trimCommon()
if len(common) > 0 {
2023-01-17 12:44:14 +00:00
f, err := m.EnsureField(common)
2023-01-16 11:52:37 +00:00
if err != nil {
return nil, err
}
2023-01-18 01:47:47 +00:00
if _, ok := f.Composite.(*Array); ok {
2023-01-16 11:52:37 +00:00
return nil, errors.New("cannot index into array")
}
2023-01-18 01:47:47 +00:00
f_m := ToMap(f)
if f_m == nil {
f_m = &Map{
parent: f,
}
f.Composite = f_m
2023-01-16 11:52:37 +00:00
}
2023-01-18 01:47:47 +00:00
return f_m.EnsureEdge(eid)
}
2023-01-16 11:52:37 +00:00
eid.Index = nil
ea := m.GetEdges(eid)
index := len(ea)
eid.Index = &index
e := &Edge{
parent: m,
ID: eid,
}
m.Edges = append(m.Edges, e)
return e, nil
}
2023-01-11 19:05:50 +00:00
2023-01-18 01:39:31 +00:00
func (ir *IR) ast() d2ast.Node {
return ir.Map.ast()
}
func (s *Scalar) ast() d2ast.Node {
return s.Value
}
func (f *Field) ast() d2ast.Node {
k := &d2ast.Key{
Key: &d2ast.KeyPath{
Path: []*d2ast.StringBox{
d2ast.MakeValueBox(d2ast.RawString(f.Name, true)).StringBox(),
},
},
2023-01-11 19:05:50 +00:00
}
if f.Primary != nil {
k.Primary = d2ast.MakeValueBox(f.Primary.ast().(d2ast.Value)).ScalarBox()
}
if f.Composite != nil {
k.Value = d2ast.MakeValueBox(f.Composite.ast().(d2ast.Value))
}
return k
2023-01-11 19:05:50 +00:00
}
2023-01-16 11:52:37 +00:00
func (e *Edge) ast() d2ast.Node {
astEdge := &d2ast.Edge{}
astEdge.Src = d2ast.MakeKeyPath(e.ID.SrcPath)
if e.ID.SrcArrow {
astEdge.SrcArrow = "<"
2023-01-16 11:52:37 +00:00
}
astEdge.Dst = d2ast.MakeKeyPath(e.ID.DstPath)
if e.ID.DstArrow {
astEdge.DstArrow = ">"
2023-01-16 11:52:37 +00:00
}
k := &d2ast.Key{
Edges: []*d2ast.Edge{astEdge},
}
if e.Primary != nil {
k.Primary = d2ast.MakeValueBox(e.Primary.ast().(d2ast.Value)).ScalarBox()
}
if e.Map != nil {
k.Value = d2ast.MakeValueBox(e.Map.ast().(*d2ast.Map))
}
return k
}
func (a *Array) ast() d2ast.Node {
if a == nil {
return nil
}
astArray := &d2ast.Array{}
for _, av := range a.Values {
astArray.Nodes = append(astArray.Nodes, d2ast.MakeArrayNodeBox(av.ast().(d2ast.ArrayNode)))
}
return astArray
}
func (m *Map) ast() d2ast.Node {
if m == nil {
return nil
}
astMap := &d2ast.Map{}
2023-01-18 01:39:31 +00:00
if m.Root() {
2023-01-17 12:44:14 +00:00
astMap.Range = d2ast.MakeRange(",0:0:0-1:0:0")
} else {
astMap.Range = d2ast.MakeRange(",1:0:0-2:0:0")
}
for _, f := range m.Fields {
astMap.Nodes = append(astMap.Nodes, d2ast.MakeMapNodeBox(f.ast().(d2ast.MapNode)))
}
for _, e := range m.Edges {
astMap.Nodes = append(astMap.Nodes, d2ast.MakeMapNodeBox(e.ast().(d2ast.MapNode)))
}
return astMap
2023-01-16 11:52:37 +00:00
}
2023-01-16 15:45:13 +00:00
2023-01-17 12:44:14 +00:00
func (m *Map) appendFieldReferences(i int, kp *d2ast.KeyPath, refctx *RefContext) {
2023-01-16 15:45:13 +00:00
sb := kp.Path[i]
2023-01-17 12:44:14 +00:00
f := m.GetField([]string{sb.Unbox().ScalarString()})
2023-01-16 15:45:13 +00:00
if f == nil {
return
}
2023-01-17 12:44:14 +00:00
f.References = append(f.References, FieldReference{
String: sb,
2023-01-16 15:45:13 +00:00
KeyPath: kp,
Context: refctx,
})
2023-01-17 11:05:56 +00:00
if i+1 == len(kp.Path) {
return
}
2023-01-18 01:47:47 +00:00
f_m := ToMap(f)
if f_m != nil {
2023-01-17 12:44:14 +00:00
f_m.appendFieldReferences(i+1, kp, refctx)
2023-01-16 15:45:13 +00:00
}
}
func (m *Map) appendEdgeReferences(e *Edge, refctx *RefContext) {
2023-01-17 11:05:56 +00:00
e.References = append(e.References, EdgeReference{
2023-01-16 15:45:13 +00:00
Context: refctx,
})
2023-01-17 12:44:14 +00:00
m.appendFieldReferences(0, refctx.Edge.Src, refctx)
m.appendFieldReferences(0, refctx.Edge.Dst, refctx)
}
2023-01-18 01:39:31 +00:00
func ToMap(n Node) *Map {
switch n := n.(type) {
case *Map:
return n
case *IR:
return n.Map
case *Field:
return ToMap(n.Composite)
case *Edge:
return n.Map
default:
return nil
}
}
func ToScalar(n Node) *Scalar {
switch n := n.(type) {
case *Field:
return n.Primary
case *Edge:
return n.Primary
default:
return nil
}
}
func ParentMap(n Node) *Map {
2023-01-17 12:44:14 +00:00
for n.Parent() != nil {
n = n.Parent()
if n_m, ok := n.(*Map); ok {
return n_m
}
}
return nil
}
2023-01-18 01:39:31 +00:00
func ParentField(n Node) *Field {
2023-01-17 12:44:14 +00:00
for n.Parent() != nil {
n = n.Parent()
if n_f, ok := n.(*Field); ok {
return n_f
}
}
return nil
}
func countUnderscores(p []string) int {
var count int
for _, el := range p {
if el != "_" {
break
}
count++
}
return count
2023-01-16 15:45:13 +00:00
}