Documentation
¶
Index ¶
- Constants
- Variables
- func AncestorNameSimilarity(t1, t2 *treesitter.ASTNode) int
- func BottomUp(t1Root, t2Root *treesitter.ASTNode, m *Mapping, minDice float64)
- func ChawatheSimilarity(t1, t2 *treesitter.ASTNode, m map[*treesitter.ASTNode]*treesitter.ASTNode) float64
- func CombineMatches(dst [][2]int, prefix int, middle [][2]int, endA, endB, lenA int) [][2]int
- func CommentSimilarity(s1, s2 string) float64
- func CompatiblePairRoles(n1, n2 *treesitter.ASTNode) bool
- func ContestContainers(t1Root, t2Root *treesitter.ASTNode, m *Mapping, part *LinePartition)
- func Dice(t1, t2 *treesitter.ASTNode, m map[*treesitter.ASTNode]*treesitter.ASTNode) float64
- func FindEnclosingScope(n *treesitter.ASTNode, r *rules.Rules) *treesitter.ASTNode
- func FindEnclosingStatement(n *treesitter.ASTNode, r *rules.Rules) *treesitter.ASTNode
- func FindImmediateStatement(n *treesitter.ASTNode, r *rules.Rules) *treesitter.ASTNode
- func FprintMappings(w io.Writer, r *MatchResult) error
- func GetEnclosingDeclaration(n *treesitter.ASTNode) *treesitter.ASTNode
- func HasLongLeafToken(n *treesitter.ASTNode) bool
- func Height(n *treesitter.ASTNode) int
- func IsScopePreserved(ms *Mapping, n1, n2 *treesitter.ASTNode, r1, r2 *rules.Rules) bool
- func Isomorphic(a, b *treesitter.ASTNode) bool
- func LCS(seq1, seq2 []*treesitter.ASTNode, eq eqFunc) [][2]*treesitter.ASTNode
- func LCSLabel(seq1, seq2 []*treesitter.ASTNode) [][2]*treesitter.ASTNode
- func LCSStructure(seq1, seq2 []*treesitter.ASTNode, m *Mapping) [][2]*treesitter.ASTNode
- func LeafSimilarity(a, b *treesitter.ASTNode) float64
- func LineDiff(linesA, linesB []string) map[int]int
- func MatchContainerKeywords(t1Root, t2Root *treesitter.ASTNode, m *Mapping)
- func MatchUnmatchedLeaves(t1Root, t2Root *treesitter.ASTNode, m *Mapping, part *LinePartition)
- func NearestMatchedAncestor(n *treesitter.ASTNode, m *Mapping, isDst bool) *treesitter.ASTNode
- func Recover(t1, t2 *treesitter.ASTNode, m *Mapping)
- func RecoverCohortSiblings(t1Root, t2Root *treesitter.ASTNode, m *Mapping)
- func RecoverGlueAnchors(m *Mapping)
- func ReleaseSeqScratch(s *SeqScratch)
- func ReleaseWordDiffScratch(s *WordDiffScratch)
- func RevokeOrphanedGlue(m *Mapping)
- func RollupMatchedContainers(t1Root, t2Root *treesitter.ASTNode, m *Mapping)
- func RunZSRecovery(t1, t2 *treesitter.ASTNode, m *Mapping)
- func SharedMatchedAncestor(t1, t2 *treesitter.ASTNode, m *Mapping) (*treesitter.ASTNode, *treesitter.ASTNode)
- func SimpleRecovery(t1, t2 *treesitter.ASTNode, m *Mapping)
- func StructureIsomorphic(a, b *treesitter.ASTNode) bool
- func TopDown(t1Root, t2Root *treesitter.ASTNode, minHeight int, m *Mapping, ...)
- func TrimBounds(n, m int, eq func(i, j int) bool) (prefix, endA, endB int)
- func TrimPrefix(n, m int, eq func(i, j int) bool) int
- func TrimSliceBounds[T comparable](a, b []T) (prefix, endA, endB int)
- func TrimSuffix(n, m, prefix int, eq func(i, j int) bool) (endA, endB int)
- func TypesMatch(t1, t2 string, r *rules.Rules) bool
- func Unquote(s string) string
- type AffinityWeights
- type LinePartition
- func (p *LinePartition) AttachRoots(rootA, rootB *treesitter.ASTNode)
- func (p *LinePartition) CalibratedDrift(rowA, rowB int) int
- func (p *LinePartition) CanMatch(n1, n2 *treesitter.ASTNode) bool
- func (p *LinePartition) IsGroup1A(n1 *treesitter.ASTNode) (bool, int)
- func (p *LinePartition) IsGroup1B(n2 *treesitter.ASTNode) (bool, int)
- type Mapping
- func (m *Mapping) Add(t1, t2 *treesitter.ASTNode)
- func (m *Mapping) AdjustedLineDistance(src, dst *treesitter.ASTNode) int
- func (m *Mapping) Clone() *Mapping
- func (m *Mapping) DiceSrc(t1, t2 *treesitter.ASTNode) float64
- func (m *Mapping) Dst() map[*treesitter.ASTNode]*treesitter.ASTNode
- func (m *Mapping) Get(t1 *treesitter.ASTNode) *treesitter.ASTNode
- func (m *Mapping) Has(t1 *treesitter.ASTNode) bool
- func (m *Mapping) HasDst(t2 *treesitter.ASTNode) bool
- func (m *Mapping) Remove(t1 *treesitter.ASTNode)
- func (m *Mapping) RemoveSet(nodes map[*treesitter.ASTNode]struct{})
- func (m *Mapping) Src() map[*treesitter.ASTNode]*treesitter.ASTNode
- type MappingPair
- type MatchResult
- type PairRole
- type SeqScratch
- type WordDiffScratch
- type WordOp
- type WordToken
Constants ¶
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 )
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 ¶
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
CombineMatches splices prefix anchors, offset middle matches, and suffix anchors into dst.
func CommentSimilarity ¶ added in v0.4.0
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, part *LinePartition)
ContestContainers reassigns T2 containers that got greedily claimed by an inner T1 node during bottom-up matching back to their proper outer T1 parent. If part is provided, it skips untouched Group 1 containers and keeps reassignments within line partition boundaries.
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 ¶
func Dice(t1, t2 *treesitter.ASTNode, m map[*treesitter.ASTNode]*treesitter.ASTNode) float64
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
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, m *Mapping) [][2]*treesitter.ASTNode
LCSStructure matches node sequences by type and shape (ignoring leaf labels), using child position, label similarity, and mapping state 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
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. Small subtrees (< 20 nodes) run Zhang-Shasha tree edit distance unless they are structured constructs (delimited containers, wrappers, blocks, calls, assignments, or key-value pairs), which route to SimpleRecovery instead.
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
TrimBounds trims matching heads and tails, returning the prefix length and remaining middle bounds.
func TrimPrefix ¶ added in v0.15.0
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
TrimSuffix returns the inclusive end indices (endA, endB) after stripping matching trailing items.
func TypesMatch ¶ added in v0.6.0
TypesMatch checks if t1 and t2 are the same type, falling back to the language's equivalent_types rules when they're not.
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) CalibratedDrift ¶ added in v0.16.0
func (p *LinePartition) CalibratedDrift(rowA, rowB int) int
CalibratedDrift returns the absolute line distance between rowA and rowB, adjusted for upstream line shifts using the nearest unchanged line anchor within a ±200-line window. Falls back to raw row distance if p is nil or no anchors exist.
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 (*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) 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
func (m *Mapping) Get(t1 *treesitter.ASTNode) *treesitter.ASTNode
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.
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.