Documentation
¶
Overview ¶
Package ir defines Untie's language-neutral math tree.
Index ¶
- Constants
- Variables
- func FormatPath(parts ...string) string
- func KindName(kind NodeKind) string
- func MarshalCanonical(f *Formula, limits ...source.Limits) ([]byte, error)
- func Validate(f *Formula, limits source.Limits) error
- func ValidateSource(f *Formula, src string, limits source.Limits) error
- func VisitChildren(n Node, visit func(Node))
- func Walk(n Node, fn func(Node) bool)
- func WalkFormula(f *Formula, limits source.Limits, fn func(Node) bool) error
- func WalkWithLimits(n Node, limits source.Limits, fn func(Node) bool) error
- type Accent
- type AlignMarker
- type Base
- type Box
- type Break
- type BreakKind
- type Cancel
- type CancelRole
- type Color
- type ColumnAlign
- type DelimiterSizing
- type DelimiterSizingKind
- type EquationLabel
- type EquationTag
- type ErrorNode
- type Fenced
- type FontRole
- type Formula
- type Fraction
- type FractionRole
- type FractionStyle
- type Glyph
- type Length
- func DipLength(v float64) (Length, error)
- func EmLength(v float64) (Length, error)
- func ExLength(v float64) (Length, error)
- func MuLength(v float64) (Length, error)
- func PercentLength(v float64) (Length, error)
- func PtLength(v float64) (Length, error)
- func RawLength(unit LengthUnit, value int64) Length
- type LengthUnit
- type LimitsPlacement
- type Line
- type MathClass
- type MathSize
- type Mode
- type Multiline
- type Node
- type NodeID
- type NodeKind
- type Operator
- type Overlay
- type OverlayAlignment
- type Paint
- type PaintRole
- type Phantom
- type Placeholder
- type Position
- type RGBA
- type Radical
- type Raise
- type Row
- type ScriptRole
- type Scripts
- type SizedDelimiter
- type Space
- type SpaceKind
- type Stats
- type Style
- type Table
- type TableLine
- type TableRole
- type TableRow
- type Text
- type TextClusterSource
- type Variant
Constants ¶
const FormulaTagLine = -1
FormulaTagLine identifies a tag that belongs to the complete formula rather than one source row.
Variables ¶
var ( ErrInvalidIR = errors.New("ir: invalid") ErrCycle = errors.New("ir: cycle detected") ErrTraversalLimit = errors.New("ir: traversal limit exceeded") )
var ErrInvalidLength = errors.New("ir: invalid length")
Functions ¶
func FormatPath ¶
FormatPath joins a path segment safely for diagnostics.
func MarshalCanonical ¶
MarshalCanonical returns deterministic JSON for golden tests and cache diagnostics. It is not the final public protocol. An optional limits argument overrides source.DefaultLimits.
func Validate ¶
Validate checks the full tree against structural invariants and resource limits. It does not have source text, so it can only check that ranges are structurally valid. Use ValidateSource at a parser or file-inspection boundary. A zero-value limits uses source.DefaultLimits.
func ValidateSource ¶
ValidateSource checks a formula and verifies that every attached range lies inside src. Detached ranges are permitted.
func VisitChildren ¶
VisitChildren visits direct child nodes in deterministic semantic order without allocating a child slice. The callback must not retain or mutate the tree; it may recurse with another VisitChildren call.
func Walk ¶
Walk visits n and its descendants depth-first in deterministic order. If fn returns false, that node's children are skipped. Walk stops on cycles or when the default traversal budget is exhausted. Call WalkWithLimits when the caller needs the traversal error.
func WalkFormula ¶
WalkFormula visits the formula root followed by every equation tag body in source order. Formula labels consume the shared metadata budget but have no child nodes to visit. Traversal budgets and cycle checks are shared across all entries, so metadata cannot bypass the formula's node or nesting limits.
Types ¶
type Accent ¶
type Accent struct {
Base
Body Node
Accent Node
Position Position
Stretchy bool // Source explicitly requests a stretchable accent.
NaturalFit bool // Layout must select an accent fitting the base width.
Dotless bool
ExactFrameWidth bool
}
Accent places a mark above or below content.
type AlignMarker ¶
type AlignMarker struct {
Base
}
AlignMarker marks a Typst/TeX alignment point.
func NewAlignMarker ¶
func NewAlignMarker(span source.Range) *AlignMarker
NewAlignMarker constructs an alignment marker.
type Base ¶
type Base struct {
// NodeID is an optional, opaque host-assigned semantic identity. Zero means
// unassigned. Nonzero IDs must be unique within a formula. Untie preserves
// the ID through cloning and layout and never derives it from source
// offsets.
NodeID identity.NodeID
Span source.Range
Origin source.Range
Class MathClass
Size MathSize
Cramped bool
Variant Variant
Paint Paint
Limits LimitsPlacement
LeftSpacing Length
RightSpacing Length
IgnoreAsSpace bool
// contains filtered or unexported fields
}
Base contains source and semantic properties shared by all IR nodes.
Base is embedded by every concrete node. Its unexported kind and marker methods make Node a sealed public interface.
type Box ¶
type Box struct {
Base
Body Node
Padding [4]Length // top, right, bottom, left
Fill Paint
HasFill bool
Border Paint
HasBorder bool
BorderWidth Length
Radius Length
}
Box adds spacing and optional decoration around body.
type Cancel ¶
type Cancel struct {
Base
Body Node
Cross bool
Inverted bool
Role CancelRole // Zero is a cancellation strike.
Thickness Length
}
Cancel overlays cancel strokes on content.
type CancelRole ¶
type CancelRole uint8
CancelRole distinguishes cancellation strokes from logical negation, which can share the same geometric overlay.
const ( CancelRoleStrike CancelRole = iota CancelRoleNegation )
type ColumnAlign ¶
type ColumnAlign uint8
ColumnAlign is the alignment of a table column.
const ( AlignCenter ColumnAlign = iota AlignLeft AlignRight )
type DelimiterSizing ¶
type DelimiterSizing struct {
Kind DelimiterSizingKind
Value Length
}
DelimiterSizing is a source-independent delimiter target policy. It never encodes a dialect's command names or discrete size tiers.
func AbsoluteDelimiterSizing ¶
func AbsoluteDelimiterSizing(value Length) DelimiterSizing
AbsoluteDelimiterSizing returns a target-length policy.
func ContentDelimiterSizing ¶
func ContentDelimiterSizing() DelimiterSizing
ContentDelimiterSizing returns the default content-relative policy.
func RelativeDelimiterSizing ¶
func RelativeDelimiterSizing(value Length) DelimiterSizing
RelativeDelimiterSizing returns a percentage-of-content policy.
func (DelimiterSizing) Valid ¶
func (s DelimiterSizing) Valid() bool
Valid reports whether the policy is internally consistent.
type DelimiterSizingKind ¶
type DelimiterSizingKind uint8
DelimiterSizingKind selects how an explicitly sized delimiter resolves its vertical target.
const ( // DelimiterSizingContent fits delimiters to their wrapped content. DelimiterSizingContent DelimiterSizingKind = iota // DelimiterSizingRelative multiplies the content-derived target by Value, // whose unit must be percent. DelimiterSizingRelative // DelimiterSizingAbsolute uses Value as an absolute target. Font-relative // units still resolve at the active typographic size. DelimiterSizingAbsolute )
type EquationLabel ¶ added in v0.4.0
EquationLabel is one unique formula-scoped label emitted by a frontend.
Name is the decoded host-facing key. Span covers the complete source construct that produced the label. Origin records its invocation site when macro expansion separates the two. Labels have no visible output and never resolve references implicitly.
type EquationTag ¶
type EquationTag struct {
Body Node
Span source.Range
Origin source.Range
Manual bool
Suppressed bool
Starred bool
Line int
}
EquationTag is one formula- or row-scoped tag or numbering-suppression event.
Body is normal math IR and is nil only for a suppression-only event. Line is FormulaTagLine for a tag associated with the complete formula, or a zero-based source row for multiline output. Formula-level and row-level events cannot be mixed, and row events must be ordered and unique. Document counters never enter this type.
type Formula ¶
type Formula struct {
Root Node
Tags []EquationTag
Labels []EquationLabel
}
Formula is the validated root returned by a frontend lowering pass. Tags and Labels are formula metadata rather than synthetic root children.
type Fraction ¶
type Fraction struct {
Base
Numerator Node
Denominator Node
Bar bool
Style FractionStyle
Role FractionRole // Semantic operation; zero is an ordinary fraction.
Padding Length
}
Fraction is a vertical, horizontal, skewed, or barless fraction.
type FractionRole ¶
type FractionRole uint8
FractionRole records the semantic operation represented by a fraction-shaped node. FractionStyle continues to control geometry.
const ( FractionRoleFraction FractionRole = iota FractionRoleBinomial FractionRoleStacked )
type FractionStyle ¶
type FractionStyle uint8
FractionStyle selects fraction construction.
const ( FractionVertical FractionStyle = iota FractionNoBar FractionSkewed FractionHorizontal )
type Length ¶
type Length struct {
Unit LengthUnit
Value int64
}
Length stores a signed value in millionths of its unit. Frontends may perform deterministic arithmetic before lowering, but layout converts units.
func PercentLength ¶
PercentLength constructs a percentage length, where 100 means 100%.
func RawLength ¶
func RawLength(unit LengthUnit, value int64) Length
RawLength constructs a length from millionths of unit.
func (Length) ValidateWithLimit ¶
ValidateWithLimit checks the unit and a caller-provided maximum absolute value in the length's named unit.
type LengthUnit ¶
type LengthUnit uint8
LengthUnit names the unit of an unresolved semantic length.
const ( LengthZero LengthUnit = iota LengthEm LengthEx LengthMu LengthPt LengthDip LengthPercent )
type LimitsPlacement ¶
type LimitsPlacement uint8
LimitsPlacement controls visual placement only: whether scripts are rendered beside a base or above/below it. It does not change ScriptRole semantics.
const ( LimitsAuto LimitsPlacement = iota LimitsAlways LimitsNever // LimitsDisplay places scripts above/below only in display style. Unlike // Auto, it does not depend on the base atom's class. LimitsDisplay )
type Multiline ¶
Multiline is a set of rows used for aligned/gathered math without a table's column grid.
type Node ¶
Node is a sealed language-neutral math node.
type NodeID ¶ added in v0.4.0
NodeID is the canonical IR name for an opaque host-assigned node identity. Zero means unassigned.
type NodeKind ¶
type NodeKind uint8
NodeKind is the stable discriminator for a node family.
const ( KindRow NodeKind = iota + 1 KindGlyph KindText KindOperator KindSpace KindFraction KindRadical KindScripts KindFenced KindAccent KindLine KindCancel KindTable KindMultiline KindStyle KindColor KindBox KindPhantom KindError KindPlaceholder KindBreak KindAlignMarker KindSizedDelimiter KindOverlay KindRaise )
type Overlay ¶ added in v0.4.0
type Overlay struct {
Base
Body Node
Alignment OverlayAlignment
}
Overlay places body at a zero-width insertion point.
The body may extend to either side according to Alignment. Its vertical metrics participate in the surrounding layout, but its horizontal advance does not. Use Raise when content must preserve its advance and only shift vertically.
func NewOverlay ¶ added in v0.4.0
func NewOverlay(span source.Range, body Node, alignment OverlayAlignment) *Overlay
NewOverlay constructs zero-width horizontally positioned content.
type OverlayAlignment ¶ added in v0.4.0
type OverlayAlignment uint8
OverlayAlignment positions zero-width content relative to its insertion point. It controls horizontal placement only; overlay content preserves its own vertical metrics and ink.
const ( // OverlayStart places the body's left edge at the insertion point. OverlayStart OverlayAlignment = iota // OverlayCenter centers the body on the insertion point. OverlayCenter // OverlayEnd places the body's right edge at the insertion point. OverlayEnd )
type Placeholder ¶
Placeholder draws a missing or unavailable content box.
func NewPlaceholder ¶
func NewPlaceholder(span source.Range, reason string) *Placeholder
NewPlaceholder constructs a placeholder.
type Raise ¶ added in v0.4.0
Raise shifts body vertically without changing its horizontal advance.
Amount is a signed source length; positive values move body upward. The resulting ascent and descent are clamped at the baseline, while visible ink outside those metrics remains available to overflow reporting.
type ScriptRole ¶
type ScriptRole uint8
ScriptRole identifies the semantic purpose of attached scripts independently of visual placement. For example, explicit \nolimits or Typst scripts() may place operator bounds beside the base without changing them from limits.
const ( ScriptRoleOrdinary ScriptRole = iota ScriptRoleLimits ScriptRoleOverlay ScriptRoleBraceLabel )
type Scripts ¶
type Scripts struct {
Base
BaseItem Node
Top Node
Bottom Node
TopLeft Node
BottomLeft Node
TopRight Node
BottomRight Node
Role ScriptRole // Semantic script purpose; zero is an ordinary script.
}
Scripts attaches scripts and limits to a base.
type SizedDelimiter ¶
type SizedDelimiter struct {
Base
Text string
Sizing DelimiterSizing
}
SizedDelimiter is one standalone delimiter with an explicit target policy. It is distinct from an ordinary delimiter atom and from a paired Fenced group.
func NewSizedDelimiter ¶
func NewSizedDelimiter(span source.Range, text string, sizing DelimiterSizing) *SizedDelimiter
NewSizedDelimiter constructs a standalone explicitly sized delimiter.
type Stats ¶
type Stats struct {
Nodes int
Tags int
Labels int
MaxDepth int
MaxTextBytes int
MaxDimensionValue int64 // Absolute fixed-point value in millionths of a unit.
MaxTableCells int
// GlyphCapacity is a conservative hint for materialized glyph fragments.
// Text runs count source bytes, so the value may exceed the shaped output.
GlyphCapacity int
}
Stats is the immutable resource-envelope summary produced while validating a formula. It lets parser-owned snapshots answer stricter configured-limit checks without traversing the full IR again. Values are extrema, not totals, except Nodes, Tags, and Labels.
func ValidateSourceWithStats ¶
ValidateSourceWithStats validates f against src and returns its resource envelope.
func ValidateWithStats ¶
ValidateWithStats validates f and returns its resource envelope.
func (Stats) WithinLimits ¶
WithinLimits reports whether a formula with these extrema satisfies limits. It is a conservative envelope: a true result is sufficient to skip the full configured-limit traversal, while false requires a diagnostic-producing pass.
type Style ¶
type Style struct {
Base
Body Node
SetSize bool
NewSize MathSize
SetCramped bool
Cramped bool
// SetFontSize applies an explicit font-size scale to body. FontSize is a
// non-negative percentage of the root host font size; 100% is the root
// size. Unlike math Size, it scales text and math content uniformly.
SetFontSize bool
FontSize Length
}
Style applies an explicit math style to body.
type Table ¶
type Table struct {
Base
Rows []TableRow
Role TableRole // Semantic grid kind; zero preserves matrix behavior.
Columns []ColumnAlign
RowGap Length
ColumnGap Length
Horizontal []TableLine
Vertical []TableLine
}
Table is a matrix, array, cases group, or aligned rows.
type TableRole ¶
type TableRole uint8
TableRole identifies the semantic construct represented by a table grid.
type TableRow ¶
type TableRow struct {
Cells []Node
}
TableRow is one row of a table. Cells may contain AlignMarker nodes.
type Text ¶
type Text struct {
Base
Text string
Font FontRole
Tracking Length
// Clusters partitions Text into contiguous UTF-8 byte ranges and maps each
// range to its absolute source range. Clusters are in logical text order;
// shaped glyphs may later appear in a different visual order. An empty
// slice means no parser-authored source map is available and layout uses
// the node-level hit fallback.
Clusters []TextClusterSource
}
Text is a shaped text-mode run.
type TextClusterSource ¶ added in v0.4.0
TextClusterSource maps one contiguous byte range in Text to the source range that produced it.
A non-empty map must cover Text completely, preserve text order, and contain non-overlapping source ranges. A parser may leave the map empty when it cannot prove those invariants; it must not guess offsets from delimiters.
func NormalizeTextClusters ¶ added in v0.4.0
func NormalizeTextClusters(text string, clusters []TextClusterSource) []TextClusterSource
NormalizeTextClusters validates a text cluster map and returns a copy in canonical order. Adjacent entries whose source ranges overlap are coalesced, allowing macro-expanded text to retain a useful invocation-level map without emitting overlapping editor hits.
Nil is returned when the input does not completely partition text at UTF-8 boundaries, contains an invalid source range, or has source ranges that cannot be ordered without losing information. Callers must leave the Text map empty in that case and rely on the node-level hit fallback.