engine

package
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 12 Imported by: 0 modules, 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

Index

Constants

View Source
const (
	// DefaultSeqDPCapacity fits up to 128x128 matrices (16,384 ints).
	DefaultSeqDPCapacity = 16384
	// MaxPooledSeqDPCapacity caps pooled buffers at 2 MB (256K ints) so one giant diff doesn't bloat the pool forever.
	MaxPooledSeqDPCapacity = 262144
)
View Source
const (
	// MaxTokensPerLine is the maximum number of tokens allowed per line before
	// the circuit breaker trips and falls back to whole-line diffing.
	MaxTokensPerLine = 120
)

Word diff limits and FNV-1a hash constants.

Variables

View Source
var DefaultAffinityWeights = AffinityWeights{
	Sim:        0.30,
	Dice:       0.25,
	Scope:      0.25,
	Pos:        0.10,
	Label:      0.10,
	KeyBonus:   0.35,
	DepthCoeff: 0.20,
}

DefaultAffinityWeights is the default set of scoring weights used by candidate selection. Exported so callers can use it as a baseline for language-specific tuning.

Functions

func AncestorNameSimilarity

func AncestorNameSimilarity(t1, t2 *treesitter.ASTNode) int

AncestorNameSimilarity counts matching ancestor identifiers to break ties in top-down matching. Stops at the nearest container declaration so file-level globals don't leak into local scope comparisons.

func BottomUp

func BottomUp(
	t1Root, t2Root *treesitter.ASTNode,
	m *Mapping,
	minDice float64,
)

BottomUp pairs unmatched container nodes in post-order when they share matched children, running recovery on newly matched blocks.

func ChawatheSimilarity

func ChawatheSimilarity(t1, t2 *treesitter.ASTNode, m map[*treesitter.ASTNode]*treesitter.ASTNode) float64

ChawatheSimilarity computes the Chawathe similarity coefficient between two subtrees given the current mapping set m (maps T1 nodes -> T2 nodes).

chawathe(t1, t2, m) = |{t ∈ s(t1) | (t, t2') ∈ m for some t2'}| / max(|s(t1)|, |s(t2)|)

func CombineMatches added in v0.15.0

func CombineMatches(dst [][2]int, prefix int, middle [][2]int, endA, endB, lenA int) [][2]int

CombineMatches splices prefix anchors, offset middle matches, and suffix anchors into dst.

func CommentSimilarity added in v0.4.0

func CommentSimilarity(s1, s2 string) float64

CommentSimilarity returns the bigram Dice coefficient for two cleaned comment strings.

func CompatiblePairRoles added in v0.6.0

func CompatiblePairRoles(n1, n2 *treesitter.ASTNode) bool

CompatiblePairRoles reports whether n1 and n2 can match without crossing key/value boundaries.

func ContestContainers added in v0.5.0

func ContestContainers(t1Root, t2Root *treesitter.ASTNode, m *Mapping)

ContestContainers reassigns T2 containers that got greedily claimed by an inner T1 node during bottom-up matching back to their proper outer T1 parent.

Example: deleting an if-block can trick BottomUp into matching the if's inner block to the outer function body (if they share something like a throw). That leaves the real function body unmapped and generates a mess of spurious Move actions.

func Dice

Dice computes the Dice similarity coefficient between two subtrees given the current mapping set m (maps T1 nodes -> T2 nodes).

dice(t1, t2, m) = 2 × |{t ∈ s(t1) | (t, t2') ∈ m for some t2'}| / (|s(t1)| + |s(t2)|)

func FindEnclosingScope added in v0.8.0

func FindEnclosingScope(n *treesitter.ASTNode, r *rules.Rules) *treesitter.ASTNode

FindEnclosingScope climbs the parent hierarchy to find the nearest enclosing block, declaration, or wrapper.

func FindEnclosingStatement added in v0.10.0

func FindEnclosingStatement(n *treesitter.ASTNode, r *rules.Rules) *treesitter.ASTNode

FindEnclosingStatement walks up from n to find the statement sitting directly under a block or root container.

func FindImmediateStatement added in v0.14.0

func FindImmediateStatement(n *treesitter.ASTNode, r *rules.Rules) *treesitter.ASTNode

FindImmediateStatement returns the nearest enclosing statement or branch. Unlike FindEnclosingStatement, it stops at chained else-if branches or case clauses instead of climbing all the way to the enclosing block.

func FprintMappings

func FprintMappings(w io.Writer, r *MatchResult) error

func GetEnclosingDeclaration added in v0.6.0

func GetEnclosingDeclaration(n *treesitter.ASTNode) *treesitter.ASTNode

GetEnclosingDeclaration traverses up from n to find the nearest ancestor registered in rules.Declarations or rules.LocalVarDeclarations.

func HasLongLeafToken added in v0.5.0

func HasLongLeafToken(n *treesitter.ASTNode) bool

HasLongLeafToken reports whether a subtree contains any non-trivial leaf label with length > 3.

func Height

func Height(n *treesitter.ASTNode) int

Height returns the height of a subtree rooted at n. A leaf has height 1.

func IsScopePreserved added in v0.8.0

func IsScopePreserved(ms *Mapping, n1, n2 *treesitter.ASTNode, r1, r2 *rules.Rules) bool

IsScopePreserved reports whether n1 and n2 reside within corresponding (mapped) enclosing scopes.

func Isomorphic

func Isomorphic(a, b *treesitter.ASTNode) bool

Isomorphic returns true if both subtrees match in type, label, and structure.

func LCS added in v0.4.0

func LCS(seq1, seq2 []*treesitter.ASTNode, eq eqFunc) [][2]*treesitter.ASTNode

LCS computes the longest common subsequence of two node sequences using a custom equality predicate.

func LCSLabel

func LCSLabel(seq1, seq2 []*treesitter.ASTNode) [][2]*treesitter.ASTNode

LCSLabel matches node sequences by type, label, and structure.

func LCSStructure

func LCSStructure(seq1, seq2 []*treesitter.ASTNode) [][2]*treesitter.ASTNode

LCSStructure matches node sequences by type and shape (ignoring leaf labels), using child position and label similarity to resolve ambiguous matches.

func LeafSimilarity added in v0.5.0

func LeafSimilarity(a, b *treesitter.ASTNode) float64

LeafSimilarity returns the Dice coefficient of non-trivial leaf labels between subtrees a and b.

func LineDiff added in v0.4.0

func LineDiff(linesA, linesB []string) map[int]int

LineDiff matches corresponding line indices between linesA and linesB using trimmed LCS, sliding change boundaries to blank lines and braces via indent heuristics.

func MatchContainerKeywords added in v0.5.0

func MatchContainerKeywords(t1Root, t2Root *treesitter.ASTNode, m *Mapping)

MatchContainerKeywords maps unmapped keyword children between mapped parent containers.

func MatchUnmatchedLeaves

func MatchUnmatchedLeaves(t1Root, t2Root *treesitter.ASTNode, m *Mapping, part *LinePartition)

MatchUnmatchedLeaves pairs unmatched leaf nodes of the same type and label using parent Dice similarity and positional scores to break ties. Leaves under unmatched parents are allowed if they share a matched ancestor.

func NearestMatchedAncestor

func NearestMatchedAncestor(n *treesitter.ASTNode, m *Mapping, isDst bool) *treesitter.ASTNode

NearestMatchedAncestor finds the closest ancestor of n that is present in the mapping. If isDst is true, it checks m.HasDst; otherwise it checks m.Has.

func Recover added in v0.4.0

func Recover(t1, t2 *treesitter.ASTNode, m *Mapping)

Recover aligns unmatched nodes inside a matched container pair. Uses Zhang-Shasha (1989) tree edit distance as a last-chance fallback on tiny subtrees (< 20 nodes), and uses SimpleRecovery (Sibling LCS) on larger subtrees.

func RecoverCohortSiblings added in v0.12.0

func RecoverCohortSiblings(t1Root, t2Root *treesitter.ASTNode, m *Mapping)

RecoverCohortSiblings pairs unmatched statements that moved alongside an anchor into another block. Pass 1 handles exact isomorphic siblings. Pass 2 pairs relocated statements (like in extracted functions) that share assigned variable names or structural similarity, keeping relative order.

func RecoverGlueAnchors added in v0.11.0

func RecoverGlueAnchors(m *Mapping)

RecoverGlueAnchors pairs unmapped parent containers when their operands or body blocks already match, keeping shared operators and recovering any remaining children.

func ReleaseSeqScratch added in v0.15.0

func ReleaseSeqScratch(s *SeqScratch)

ReleaseSeqScratch returns s to the pool, shrinking it if it grew past MaxPooledSeqDPCapacity.

func ReleaseWordDiffScratch added in v0.15.0

func ReleaseWordDiffScratch(s *WordDiffScratch)

ReleaseWordDiffScratch returns a WordDiffScratch to the pool after resetting slice lengths.

func RevokeOrphanedGlue added in v0.10.0

func RevokeOrphanedGlue(m *Mapping)

RevokeOrphanedGlue unmaps glue tokens (operators, punctuation, keywords) that matched across different containers, and drops moving containers that are held solely by glue. Glue can help anchor stationary constructs, but it shouldn't move on its own or drag an unmapped container into a new scope.

func RollupMatchedContainers added in v0.5.0

func RollupMatchedContainers(t1Root, t2Root *treesitter.ASTNode, m *Mapping)

RollupMatchedContainers pairs unmatched container nodes in post-order when their mapped children predominantly belong to the same unmatched parent container in T2.

func RunZSRecovery added in v0.4.0

func RunZSRecovery(t1, t2 *treesitter.ASTNode, m *Mapping)

RunZSRecovery runs Zhang-Shasha (1989) tree edit distance on small subtrees t1 and t2 and adds optimal node mappings to m.

func SharedMatchedAncestor added in v0.5.0

func SharedMatchedAncestor(t1, t2 *treesitter.ASTNode, m *Mapping) (*treesitter.ASTNode, *treesitter.ASTNode)

SharedMatchedAncestor finds the nearest pair of ancestors (a1, a2) of t1 and t2 such that a1 in T1 is mapped to a2 in T2.

func SimpleRecovery

func SimpleRecovery(t1, t2 *treesitter.ASTNode, m *Mapping)

SimpleRecovery maps unmatched children inside container pair (t1, t2) using positional anchors, label/structural LCS, and unique-type matching.

func StructureIsomorphic

func StructureIsomorphic(a, b *treesitter.ASTNode) bool

StructureIsomorphic returns true if both subtrees match in shape and node types, ignoring leaf labels.

func TopDown

func TopDown(
	t1Root, t2Root *treesitter.ASTNode,
	minHeight int,
	m *Mapping,
	part *LinePartition,
)

TopDown matches largest isomorphic subtrees top-down by height.

func TrimBounds added in v0.15.0

func TrimBounds(n, m int, eq func(i, j int) bool) (prefix, endA, endB int)

TrimBounds trims matching heads and tails, returning the prefix length and remaining middle bounds.

func TrimPrefix added in v0.15.0

func TrimPrefix(n, m int, eq func(i, j int) bool) int

TrimPrefix returns the count of leading items shared by sequences of lengths n and m.

func TrimSliceBounds added in v0.15.0

func TrimSliceBounds[T comparable](a, b []T) (prefix, endA, endB int)

TrimSliceBounds trims matching heads and tails across two comparable slices.

func TrimSuffix added in v0.15.0

func TrimSuffix(n, m, prefix int, eq func(i, j int) bool) (endA, endB int)

TrimSuffix returns the inclusive end indices (endA, endB) after stripping matching trailing items.

func TypesMatch added in v0.6.0

func TypesMatch(t1, t2 string, r *rules.Rules) bool

TypesMatch checks if t1 and t2 are the same type, falling back to the language's equivalent_types rules when they're not.

func Unquote added in v0.6.0

func Unquote(s string) string

Unquote strips surrounding quotes from s if the start and end match.

Types

type AffinityWeights added in v0.8.0

type AffinityWeights struct {
	Sim        float64 // Chawathe leaf similarity weight
	Dice       float64 // Subtree descendant Dice weight
	Scope      float64 // Scope proximity weight
	Pos        float64 // Sibling index alignment weight
	Label      float64 // Leaf label similarity weight
	KeyBonus   float64 // Exact key match bonus for pair nodes
	DepthCoeff float64 // Linear capped penalty coefficient for relative depth divergence
}

AffinityWeights holds the scoring weights used to rank bottom-up candidates.

type LinePartition added in v0.4.0

type LinePartition struct {
	// contains filtered or unexported fields
}

func NewLinePartition added in v0.4.0

func NewLinePartition(srcA, srcB []byte) *LinePartition

func (*LinePartition) AttachRoots added in v0.15.0

func (p *LinePartition) AttachRoots(rootA, rootB *treesitter.ASTNode)

AttachRoots records declaration scopes so lines moved across functions aren't treated as untouched stationary code (Group 1).

func (*LinePartition) CanMatch added in v0.4.0

func (p *LinePartition) CanMatch(n1, n2 *treesitter.ASTNode) bool

CanMatch checks if two nodes are allowed to pair up: - Untouched nodes (Group 1) only match untouched nodes on corresponding lines. - Edited nodes (Group 2) only match other edited nodes. - Cross-matching between untouched and edited nodes is forbidden.

func (*LinePartition) IsGroup1A added in v0.4.0

func (p *LinePartition) IsGroup1A(n1 *treesitter.ASTNode) (bool, int)

IsGroup1A returns true if all lines spanned by n1 in file A are non-edited lines.

func (*LinePartition) IsGroup1B added in v0.4.0

func (p *LinePartition) IsGroup1B(n2 *treesitter.ASTNode) (bool, int)

IsGroup1B returns true if all lines spanned by n2 in file B are non-edited lines.

type Mapping

type Mapping struct {
	Pairs []MappingPair
	// contains filtered or unexported fields
}

Mapping is a 1-1 node mapping between T1 nodes and T2 nodes. Pairs preserves insertion order for deterministic iteration.

func NewMapping

func NewMapping() *Mapping

NewMapping allocates an empty 1:1 AST node mapping.

func (*Mapping) Add

func (m *Mapping) Add(t1, t2 *treesitter.ASTNode)

Add registers the t1→t2 pair, enforcing strict 1:1 bijection. If t2 was already claimed by a different t1, that old mapping is evicted. If t1 was already mapped to a different t2, that old destination is replaced in-place to preserve insertion order.

func (*Mapping) AdjustedLineDistance added in v0.9.0

func (m *Mapping) AdjustedLineDistance(src, dst *treesitter.ASTNode) int

AdjustedLineDistance computes the relative distance in lines between src and dst, compensating for baseline line drift caused by preceding additions, deletions, and container shifts within their common enclosing scope.

func (*Mapping) Clone added in v0.9.0

func (m *Mapping) Clone() *Mapping

Clone returns an independent copy of the mapping.

func (*Mapping) DiceSrc

func (m *Mapping) DiceSrc(t1, t2 *treesitter.ASTNode) float64

DiceSrc computes dice(t1, t2) using the internal src mapping.

func (*Mapping) Dst

func (m *Mapping) Dst() map[*treesitter.ASTNode]*treesitter.ASTNode

Dst exposes the T2->T1 map.

func (*Mapping) Get added in v0.8.0

Get returns the mapped destination node for t1, or nil if none exists.

func (*Mapping) Has

func (m *Mapping) Has(t1 *treesitter.ASTNode) bool

Has reports whether t1 has been mapped to a destination node.

func (*Mapping) HasDst

func (m *Mapping) HasDst(t2 *treesitter.ASTNode) bool

HasDst reports whether t2 has been claimed as a destination node.

func (*Mapping) Remove

func (m *Mapping) Remove(t1 *treesitter.ASTNode)

Remove clears the mapping for t1 and any destination node it was paired with.

func (*Mapping) RemoveSet added in v0.11.0

func (m *Mapping) RemoveSet(nodes map[*treesitter.ASTNode]struct{})

RemoveSet drops a batch of source nodes from the mapping and cleans up Pairs in one pass.

func (*Mapping) Src

func (m *Mapping) Src() map[*treesitter.ASTNode]*treesitter.ASTNode

Src exposes the T1->T2 map for use in Dice calculations.

type MappingPair

type MappingPair struct {
	Src *treesitter.ASTNode
	Dst *treesitter.ASTNode
}

MappingPair is a single src→dst node mapping, kept for deterministic ordering.

type MatchResult

type MatchResult struct {
	Mappings *Mapping
}

func Match

func Match(t1, t2 *treesitter.ASTNode, srcA, srcB []byte, part *LinePartition) *MatchResult

type PairRole added in v0.6.0

type PairRole int

PairRole identifies whether a node acts as a key or a value inside a key-value pair.

const (
	PairRoleNone PairRole = iota
	PairRoleKey
	PairRoleValue
)

func NodePairRole added in v0.6.0

func NodePairRole(n *treesitter.ASTNode) PairRole

NodePairRole checks if n sits on the key or value side of a pair.

type SeqScratch added in v0.15.0

type SeqScratch struct {
	// contains filtered or unexported fields
}

SeqScratch holds reusable buffers for zero-alloc sequence alignment. It is not safe for concurrent use; callers should acquire per-goroutine instances.

func AcquireSeqScratch added in v0.15.0

func AcquireSeqScratch() *SeqScratch

AcquireSeqScratch borrows a SeqScratch from the pool.

func NewSeqScratch added in v0.15.0

func NewSeqScratch(initialDPCap int) *SeqScratch

NewSeqScratch creates a SeqScratch buffer with the requested initial DP capacity.

func (*SeqScratch) AlignUniform added in v0.15.0

func (s *SeqScratch) AlignUniform(n, m int, eq func(i, j int) bool) [][2]int

AlignUniform finds the longest common subsequence where every equal pair scores 1. The returned slice aliases internal scratch memory and is only valid until the next Align call or ReleaseSeqScratch.

func (*SeqScratch) AlignWeighted added in v0.15.0

func (s *SeqScratch) AlignWeighted(n, m int, weight func(i, j int) int, tieBreakDiagonal bool) [][2]int

AlignWeighted aligns sequences using a scoring function. Pairs returning 0 are skipped. When tieBreakDiagonal is true, ties select candidates closest to the diagonal |i - j|. The returned slice aliases internal scratch memory and is only valid until the next Align call or ReleaseSeqScratch.

func (*SeqScratch) Reset added in v0.15.0

func (s *SeqScratch) Reset()

Reset clears matches without reallocating.

type WordDiffScratch added in v0.15.0

type WordDiffScratch struct {
	Ops []WordOp
	// contains filtered or unexported fields
}

WordDiffScratch holds reusable pooled buffers for zero-allocation word diffing.

func AcquireWordDiffScratch added in v0.15.0

func AcquireWordDiffScratch() *WordDiffScratch

AcquireWordDiffScratch retrieves a pre-allocated WordDiffScratch from the pool.

func (*WordDiffScratch) Diff added in v0.15.0

func (s *WordDiffScratch) Diff(src, dst string) []WordOp

Diff computes word-level diff operations between src and dst using the scratch buffers. The returned operations slice is stored in s.Ops and remains valid until the next call to Diff or until s is released.

type WordOp added in v0.15.0

type WordOp struct {
	Action   string // "update", "delete", "insert"
	SrcStart int
	SrcEnd   int
	DstStart int
	DstEnd   int
}

WordOp represents a word-level diff operation within a line. Action is one of "update", "delete", or "insert".

func DiffWords added in v0.15.0

func DiffWords(src, dst string) []WordOp

DiffWords computes word-level diff operations between src and dst using pooled scratch buffers. For hot diff loops across multiple lines, prefer AcquireWordDiffScratch / ReleaseWordDiffScratch.

type WordToken added in v0.15.0

type WordToken struct {
	Hash  uint64
	Start int
	End   int
}

WordToken represents a single token in a line with byte boundaries and 64-bit FNV-1a hash.

Jump to

Keyboard shortcuts

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