d2ir

package
v0.10.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 30, 2026 License: MPL-2.0 Imports: 27 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package d2ir implements a tree data structure to keep track of the resolved value of D2 keys.

Index

Constants

View Source
const DefaultMaxEdgeExpansion int64 = 1_024

DefaultMaxEdgeExpansion is the maximum number of distinct edge-segment and endpoint combinations that edge globs may consider during one compilation. Explicit edges do not consume this budget because their work is proportional to the input size. The limit is calibrated so a sparse star at the boundary remains bounded in the built-in Dagre and ELK layouts, while larger wildcard fanout stops before layout.

View Source
const DefaultMaxEdgeExpansionWork int64 = 65_536

DefaultMaxEdgeExpansionWork is the maximum number of endpoint-pair examinations edge globs may perform, including repeated lazy replays.

View Source
const DefaultMaxGlobExpansion int64 = 65_536

DefaultMaxGlobExpansion is the maximum amount of work globs may perform during one compilation. Explicit source fields do not consume this budget.

View Source
const DefaultMaxVariableExpansion int64 = 65_536

DefaultMaxVariableExpansion is the maximum amount of work that variable substitutions and the copies they induce may add to one compilation. One work unit is one copied IR node or slice element, one forward dependency, one inserted array member, one produced string byte, one Markdown match candidate, or one byte prepared for a Markdown variable lookup pattern.

View Source
const MaxImportDepth = 128

MaxImportDepth is the maximum number of imported files permitted in one active import chain. The root source file is not counted.

Variables

View Source
var ErrImportsDisabled = errors.New("d2ir: imports are disabled; provide CompileOptions.FS to enable them")

ErrImportsDisabled is returned when D2 source requests an import but the caller did not provide CompileOptions.FS.

Functions

func ApplySequenceDeletions added in v0.10.1

func ApplySequenceDeletions(ctx context.Context, scopes []*Map, accepts func(*Field) bool) error

ApplySequenceDeletions shares null assignments among maps that declare the same participant or timeline item. The maps still have their original edges, which lets removal of an endpoint also remove its earlier messages.

func BoardIDA

func BoardIDA(n Node) (ida []d2ast.String)

BoardIDA returns the absolute path to n from the nearest board root.

func DeclarationOrder added in v0.10.1

func DeclarationOrder(n Node) ([]uint64, int)

DeclarationOrder gives the first authored occurrence of an object or connection after expanding imports and spreads, and its index in the reference list. Multiple endpoints of the same key use their literal position as a tiebreaker. Later style overrides do not move them.

func ExpandSubstitution

func ExpandSubstitution(m, resolved *Map, placeholder *Field)

func IDA

func IDA(n Node) (ida []d2ast.String)

IDA returns the absolute path to n.

func IsVar

func IsVar(n Node) bool

func OverlayEdge deprecated

func OverlayEdge(be, oe *Edge)

OverlayEdge applies one edge overlay directly to another edge.

Deprecated: construct overlays as maps and apply them with OverlayMap. OverlayEdge is an internal IR mutation detail and will be removed after one compatibility release.

func OverlayField deprecated

func OverlayField(bf, of *Field)

OverlayField applies one field overlay directly to another field.

Deprecated: construct overlays as maps and apply them with OverlayMap. OverlayField is an internal IR mutation detail and will be removed after one compatibility release.

func OverlayMap

func OverlayMap(base, overlay *Map)

func OverlaySequenceActor added in v0.10.1

func OverlaySequenceActor(dst *Map, field *Field)

OverlaySequenceActor moves an actor out of a v2 message frame. Its attributes may already have declarations in the diagram or another frame. Unlike a normal overlay, traversal order says nothing about which declaration wins.

func ParentShape

func ParentShape(n Node) string

ParentShape returns the canonical name of the shape of the nearest field containing n that sets one (see d2target.CanonicalShape).

func ParseAnimateInterval added in v0.10.0

func ParseAnimateInterval(value string) (int64, bool)

ParseAnimateInterval returns the source interval in milliseconds. A bare integer uses milliseconds, matching the CLI flag.

func RelIDA

func RelIDA(p, n Node) (ida []d2ast.String)

RelIDA returns the path to n relative to p.

func ReserveVariableExpansionAliases added in v0.10.0

func ReserveVariableExpansionAliases(ctx context.Context, m *Map) error

ReserveVariableExpansionAliases accounts for logical IR nodes reached more than once through composite aliases. It must run before graph materialization, which turns those shared references into distinct graph objects.

func ReserveVariableExpansionCopy added in v0.10.0

func ReserveVariableExpansionCopy(ctx context.Context, m *Map) error

ReserveVariableExpansionCopy accounts for the logical IR nodes an automatic copy will materialize. It shares the same compilation-wide budget used by substitutions and alias materialization.

Types

type Array

type Array struct {
	Values []Value `json:"values"`
	// contains filtered or unexported fields
}

func (*Array) AST

func (a *Array) AST() d2ast.Node

func (*Array) Copy

func (a *Array) Copy(newParent Node) Node

func (*Array) Equal

func (a *Array) Equal(n2 Node) bool

func (*Array) LastPrimaryKey

func (n *Array) LastPrimaryKey() *d2ast.Key

func (*Array) LastPrimaryRef

func (n *Array) LastPrimaryRef() Reference

func (*Array) LastRef

func (n *Array) LastRef() Reference

func (*Array) Map

func (n *Array) Map() *Map

func (*Array) Parent

func (n *Array) Parent() Node

func (*Array) Primary

func (n *Array) Primary() *Scalar

func (*Array) String

func (n *Array) String() string

type BoardKind

type BoardKind string
const (
	BoardLayer    BoardKind = "layer"
	BoardScenario BoardKind = "scenario"
	BoardStep     BoardKind = "step"
)

func NodeBoardKind

func NodeBoardKind(n Node) BoardKind

NodeBoardKind reports whether n represents the root of a board. n should be *Field or *Map

type CompileOptions

type CompileOptions struct {
	// ReportGlobWarning receives non-fatal source findings after a successful full compile.
	ReportGlobWarning func(code string, r d2ast.Range, message string)
	// ReportDeprecation receives deprecation warnings discovered during IR evaluation,
	// such as deprecated shape or constraint names in glob filters.
	ReportDeprecation func(code string, r d2ast.Range, message string)
	// WarnUnmatchedGlob enables diagnostics for source style selectors that never matched.
	WarnUnmatchedGlob bool
	// Partial returns the IR built so far together with compile errors. It is
	// for language tooling. A partial IR may be incomplete and must not be rendered.
	Partial bool
	// AnimateDuration overrides the root animate-duration, in milliseconds.
	AnimateDuration *int64
	// AnimateTweens controls sampling of step and scenario transitions. Nil follows
	// the root animate-interval. False compiles only the authored endpoints.
	AnimateTweens *bool
	// Context stops parsing and compilation when canceled. A nil Context is
	// treated as context.Background().
	Context  context.Context
	UTF16Pos bool
	// FixedPositionEncoding applies UTF16Pos to imports in all supported encodings.
	FixedPositionEncoding bool
	// MaxVariableExpansion bounds work added by substitutions and automatic
	// copies. Zero uses DefaultMaxVariableExpansion.
	MaxVariableExpansion int64
	// MaxGlobExpansion bounds work performed by glob matching and
	// materialization. Zero uses DefaultMaxGlobExpansion. Explicit source fields
	// are not counted as materialization work.
	MaxGlobExpansion int64
	// MaxEdgeExpansion bounds distinct edge-segment and endpoint combinations
	// considered by edge globs. Zero uses DefaultMaxEdgeExpansion. Explicit edges
	// do not consume this budget.
	MaxEdgeExpansion int64
	// MaxEdgeExpansionWork bounds all endpoint-pair examinations performed by
	// edge globs, including lazy replays. Zero uses DefaultMaxEdgeExpansionWork.
	MaxEdgeExpansionWork int64
	// FS resolves imports. Nil disables imports. The lib/localfile package
	// provides rooted and explicit unrestricted host-filesystem policies. A filesystem
	// may implement ResolveImportPath(parent, name string) string to use its own
	// path syntax. Other filesystems receive slash-separated io/fs paths.
	FS fs.FS
}

type Composite

type Composite interface {
	Node
	Value
	// contains filtered or unexported methods
}

type Edge

type Edge struct {
	// SequenceKey retains the scoped, indexed source address through sequence actor hoisting.
	SequenceKey *d2ast.Key `json:"-"`

	ID *EdgeID `json:"edge_id"`

	Primary_ *Scalar `json:"primary,omitempty"`
	Map_     *Map    `json:"map,omitempty"`

	References []*EdgeReference `json:"references,omitempty"`
	// contains filtered or unexported fields
}

func ParentEdge

func ParentEdge(n Node) *Edge

func (*Edge) AST

func (e *Edge) AST() d2ast.Node

func (*Edge) Copy

func (e *Edge) Copy(newParent Node) Node

func (*Edge) Equal

func (e *Edge) Equal(n2 Node) bool

func (*Edge) IDString

func (e *Edge) IDString() d2ast.String

func (*Edge) ImportAST

func (e *Edge) ImportAST() d2ast.Node

func (*Edge) LastPrimaryKey

func (e *Edge) LastPrimaryKey() *d2ast.Key

func (*Edge) LastPrimaryRef

func (e *Edge) LastPrimaryRef() Reference

func (*Edge) LastRef

func (e *Edge) LastRef() Reference

func (*Edge) Map

func (n *Edge) Map() *Map

func (*Edge) Parent

func (n *Edge) Parent() Node

func (*Edge) Primary

func (n *Edge) Primary() *Scalar

func (*Edge) SetImportAST

func (e *Edge) SetImportAST(node d2ast.Node)

func (*Edge) String

func (n *Edge) String() string

type EdgeID

type EdgeID struct {
	SrcPath  []d2ast.String `json:"src_path"`
	SrcArrow bool           `json:"src_arrow"`

	DstPath  []d2ast.String `json:"dst_path"`
	DstArrow bool           `json:"dst_arrow"`

	// If nil, then any EdgeID with equal src/dst/arrows matches.
	Index *int `json:"index"`
	Glob  bool `json:"glob"`
}

func NewEdgeIDs

func NewEdgeIDs(k *d2ast.Key) (eida []*EdgeID)

func (*EdgeID) AST added in v0.10.1

func (eid *EdgeID) AST() *d2ast.Edge

func (*EdgeID) Copy

func (eid *EdgeID) Copy() *EdgeID

func (*EdgeID) Match

func (eid *EdgeID) Match(eid2 *EdgeID) bool

type EdgeReference

type EdgeReference struct {
	Context_       *RefContext `json:"context"`
	DueToGlob_     bool        `json:"due_to_glob"`
	DueToLazyGlob_ bool        `json:"due_to_lazy_glob"`
	// contains filtered or unexported fields
}

func (*EdgeReference) AST

func (er *EdgeReference) AST() d2ast.Node

func (*EdgeReference) Context

func (r *EdgeReference) Context() *RefContext

func (*EdgeReference) DueToGlob

func (r *EdgeReference) DueToGlob() bool

func (*EdgeReference) DueToLazyGlob

func (r *EdgeReference) DueToLazyGlob() bool

func (*EdgeReference) Primary

func (er *EdgeReference) Primary() bool

Primary returns true if the Value in Context.Key.Value corresponds to the *Edge represented by Context.Edge

type Field

type Field struct {
	Name d2ast.String `json:"name"`

	// Primary_ to avoid clashing with Primary(). We need to keep it exported for
	// encoding/json to marshal it so cannot prefix _ instead.
	Primary_  *Scalar   `json:"primary,omitempty"`
	Composite Composite `json:"composite,omitempty"`

	References []*FieldReference `json:"references,omitempty"`
	// contains filtered or unexported fields
}

func LatestPrimary added in v0.10.1

func LatestPrimary(a, b *Field) *Field

LatestPrimary returns whichever of a and b has the later primary value assignment. If only one has a primary value, that field is returned.

func ParentField

func ParentField(n Node) *Field

func (*Field) AST

func (f *Field) AST() d2ast.Node

func (*Field) Copy

func (f *Field) Copy(newParent Node) Node

func (*Field) Equal

func (f *Field) Equal(n2 Node) bool

func (*Field) ImportAST

func (f *Field) ImportAST() d2ast.Node

func (*Field) LastPrimaryKey

func (f *Field) LastPrimaryKey() *d2ast.Key

func (*Field) LastPrimaryRef

func (f *Field) LastPrimaryRef() Reference

func (*Field) LastRef

func (f *Field) LastRef() Reference

func (*Field) Map

func (n *Field) Map() *Map

func (*Field) Parent

func (n *Field) Parent() Node

func (*Field) Primary

func (n *Field) Primary() *Scalar

func (*Field) Root

func (f *Field) Root() bool

func (*Field) SequenceEndpointOnly added in v0.10.1

func (f *Field) SequenceEndpointOnly() bool

SequenceEndpointOnly reports an implicit participant introduced solely by message endpoints. Such a field beside a branch is not a branch declaration.

func (*Field) SetImportAST

func (f *Field) SetImportAST(node d2ast.Node)

func (*Field) ShapeOptionsAfterPrimary added in v0.10.1

func (f *Field) ShapeOptionsAfterPrimary() *Field

ShapeOptionsAfterPrimary returns a read-only view of f containing only shape options (and map literal opening) written at or after the assignment that established f's current shape type, or nil if no composite options remain after that assignment.

func (*Field) String

func (n *Field) String() string

type FieldReference

type FieldReference struct {
	String  d2ast.String   `json:"string"`
	KeyPath *d2ast.KeyPath `json:"key_path"`

	Context_       *RefContext `json:"context"`
	DueToGlob_     bool        `json:"due_to_glob"`
	DueToLazyGlob_ bool        `json:"due_to_lazy_glob"`
	// contains filtered or unexported fields
}

func (*FieldReference) AST

func (fr *FieldReference) AST() d2ast.Node

func (*FieldReference) Context

func (r *FieldReference) Context() *RefContext

func (*FieldReference) DueToGlob

func (r *FieldReference) DueToGlob() bool

func (*FieldReference) DueToLazyGlob

func (r *FieldReference) DueToLazyGlob() bool

func (*FieldReference) EdgeDest

func (fr *FieldReference) EdgeDest() bool

func (*FieldReference) InEdge

func (fr *FieldReference) InEdge() bool

func (*FieldReference) KeyPathIndex

func (fr *FieldReference) KeyPathIndex() int

func (*FieldReference) Primary

func (fr *FieldReference) Primary() bool

Primary returns true if the Value in Context.Key.Value corresponds to the Field represented by String.

type Importable

type Importable interface {
	ImportAST() d2ast.Node
	SetImportAST(d2ast.Node)
}

type Map

type Map struct {
	// TweenFrames are fully resolved, read-only samples of this board's incoming
	// transition. They are shared across IR copies, outside the authored board tree.
	TweenFrames     []*Map `json:"-"`
	TweenDurationMS int    `json:"-"`

	Fields []*Field `json:"fields"`
	Edges  []*Edge  `json:"edges"`
	// contains filtered or unexported fields
}

func Compile

func Compile(ast *d2ast.Map, opts *CompileOptions) (*Map, []string, error)

func EditGraphScopes added in v0.10.1

func EditGraphScopes(ctx context.Context, root *Map, scopes map[*Map]bool, owned bool, edit func(*Map) error) (*Map, error)

EditGraphScopes materializes selected submaps for graph normalization. A true entry selects the whole scope; false marks an ancestor on the way to one. Other maps are read-only during graph compilation and can be shared.

func ParentMap

func ParentMap(n Node) *Map

func RootMap

func RootMap(m *Map) *Map

func (*Map) AST

func (m *Map) AST() d2ast.Node

func (*Map) BoardAST added in v0.10.1

func (m *Map) BoardAST(ctx context.Context) (*d2ast.Map, error)

BoardAST builds the editor's flattened source for an authored board. A nested board can occur in several ancestors' ASTs, so reserve each logical occurrence before allocating it. AST() shares field names and scalar values and does not copy IR source-reference histories.

func (*Map) Copy

func (m *Map) Copy(newParent Node) Node

func (*Map) CopyBase

func (m *Map) CopyBase(newParent Node) *Map

CopyBase copies the map m without layers/scenarios/steps.

func (*Map) CreateEdge

func (m *Map) CreateEdge(eid *EdgeID, refctx *RefContext, c *compiler) ([]*Edge, error)

func (*Map) DeleteEdge

func (m *Map) DeleteEdge(eid *EdgeID) *Edge

func (*Map) DeleteField

func (m *Map) DeleteField(ida ...string) *Field

func (*Map) EdgeCountRecursive

func (m *Map) EdgeCountRecursive() int

func (*Map) EnsureField

func (m *Map) EnsureField(kp *d2ast.KeyPath, refctx *RefContext, create bool, c *compiler) ([]*Field, error)

EnsureField is a bit of a misnomer. It's more of a Query/Ensure combination function at this point.

func (*Map) Equal

func (m *Map) Equal(n2 Node) bool

func (*Map) FieldCountRecursive

func (m *Map) FieldCountRecursive() int

func (*Map) FindBoardRoot

func (m *Map) FindBoardRoot(path []string) *Map

func (*Map) GetClassMap

func (m *Map) GetClassMap(name string) *Map

func (*Map) GetEdges

func (m *Map) GetEdges(eid *EdgeID, refctx *RefContext, c *compiler) []*Edge

func (*Map) GetField

func (m *Map) GetField(ida ...d2ast.String) *Field

func (*Map) HasClearedField added in v0.10.1

func (m *Map) HasClearedField(name string) bool

HasClearedField reports whether the unquoted shape option name was explicitly cleared with null in this map and not subsequently reassigned.

func (*Map) HasSequenceDeletions added in v0.10.1

func (m *Map) HasSequenceDeletions() bool

HasSequenceDeletions reports whether this occurrence has field deletions to reconcile with declarations from other frames.

func (*Map) ImportAST

func (m *Map) ImportAST() d2ast.Node

func (*Map) InClass

func (m *Map) InClass(key *d2ast.Key) bool

func (*Map) IsClass

func (m *Map) IsClass() bool

func (*Map) LastPrimaryKey

func (n *Map) LastPrimaryKey() *d2ast.Key

func (*Map) LastPrimaryRef

func (n *Map) LastPrimaryRef() Reference

func (*Map) LastRef

func (n *Map) LastRef() Reference

func (*Map) Map

func (n *Map) Map() *Map

func (*Map) Parent

func (n *Map) Parent() Node

func (*Map) Primary

func (n *Map) Primary() *Scalar

func (*Map) Query

func (m *Map) Query(idStr string) (Node, error)

Query is only for tests and debugging.

func (*Map) QueryAll

func (m *Map) QueryAll(idStr string) (na []Node, _ error)

QueryAll is only for tests and debugging.

func (*Map) Root

func (m *Map) Root() bool

Root reports whether the Map is the root of the D2 tree.

func (*Map) SetImportAST

func (m *Map) SetImportAST(node d2ast.Node)

func (*Map) String

func (n *Map) String() string

type Node

type Node interface {
	Copy(newParent Node) Node
	Parent() Node
	Primary() *Scalar
	Map() *Map
	Equal(n2 Node) bool

	AST() d2ast.Node
	fmt.Stringer

	LastRef() Reference
	LastPrimaryRef() Reference
	LastPrimaryKey() *d2ast.Key
	// contains filtered or unexported methods
}

Most errors returned by a node should be created with d2parser.Errorf to indicate the offending AST node.

func ParentBoard

func ParentBoard(n Node) Node

type RefContext

type RefContext struct {
	Edge     *d2ast.Edge `json:"edge"`
	Key      *d2ast.Key  `json:"key"`
	Scope    *d2ast.Map  `json:"-"`
	ScopeMap *Map        `json:"-"`
	ScopeAST *d2ast.Map  `json:"-"`
	// contains filtered or unexported fields
}

func (*RefContext) Copy

func (rc *RefContext) Copy() *RefContext

func (*RefContext) EdgeIndex

func (rc *RefContext) EdgeIndex() int

func (*RefContext) Equal

func (rc *RefContext) Equal(rc2 *RefContext) bool

type Reference

type Reference interface {

	// Most specific AST node for the reference.
	AST() d2ast.Node
	Primary() bool
	Context() *RefContext
	// Result of a glob in Context or from above.
	DueToGlob() bool
	DueToLazyGlob() bool
	// contains filtered or unexported methods
}

type Scalar

type Scalar struct {
	Value d2ast.Scalar `json:"value"`
	// BoardLinkSource retains the spelling before resolution against a declaration or import.
	BoardLinkSource string `json:"-"`
	// TweenOffset retains precision lost when formatting a numeric sample for
	// text. Continuous paint properties can use it for the unrounded value.
	TweenOffset float64 `json:"-"`
	// NumericTween identifies interpolated numbers, including samples that land on an integer.
	NumericTween bool `json:"-"`
	// contains filtered or unexported fields
}

func (*Scalar) AST

func (s *Scalar) AST() d2ast.Node

func (*Scalar) Copy

func (s *Scalar) Copy(newParent Node) Node

func (*Scalar) Equal

func (s *Scalar) Equal(n2 Node) bool

func (*Scalar) LastPrimaryKey

func (n *Scalar) LastPrimaryKey() *d2ast.Key

func (*Scalar) LastPrimaryRef

func (n *Scalar) LastPrimaryRef() Reference

func (*Scalar) LastRef

func (n *Scalar) LastRef() Reference

func (*Scalar) Map

func (n *Scalar) Map() *Map

func (*Scalar) Parent

func (n *Scalar) Parent() Node

func (*Scalar) Primary

func (n *Scalar) Primary() *Scalar

func (*Scalar) String

func (n *Scalar) String() string

type SequenceShapeCache added in v0.10.1

type SequenceShapeCache map[*Map]sequenceClassState

SequenceShapeCache resolves the same class-provided shape and branch options for glob matching and for the subsequent graph normalization.

func (*SequenceShapeCache) Value added in v0.10.1

func (cache *SequenceShapeCache) Value(m *Map, branched bool, lookup func(*Map, string) *Map) string

type Value

type Value interface {
	Node
	// contains filtered or unexported methods
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL