Path: blob/main/vendor/github.com/google/go-cmp/cmp/internal/diff/diff.go
2898 views
// Copyright 2017, The Go Authors. All rights reserved.1// Use of this source code is governed by a BSD-style2// license that can be found in the LICENSE file.34// Package diff implements an algorithm for producing edit-scripts.5// The edit-script is a sequence of operations needed to transform one list6// of symbols into another (or vice-versa). The edits allowed are insertions,7// deletions, and modifications. The summation of all edits is called the8// Levenshtein distance as this problem is well-known in computer science.9//10// This package prioritizes performance over accuracy. That is, the run time11// is more important than obtaining a minimal Levenshtein distance.12package diff1314import (15"math/rand"16"time"1718"github.com/google/go-cmp/cmp/internal/flags"19)2021// EditType represents a single operation within an edit-script.22type EditType uint82324const (25// Identity indicates that a symbol pair is identical in both list X and Y.26Identity EditType = iota27// UniqueX indicates that a symbol only exists in X and not Y.28UniqueX29// UniqueY indicates that a symbol only exists in Y and not X.30UniqueY31// Modified indicates that a symbol pair is a modification of each other.32Modified33)3435// EditScript represents the series of differences between two lists.36type EditScript []EditType3738// String returns a human-readable string representing the edit-script where39// Identity, UniqueX, UniqueY, and Modified are represented by the40// '.', 'X', 'Y', and 'M' characters, respectively.41func (es EditScript) String() string {42b := make([]byte, len(es))43for i, e := range es {44switch e {45case Identity:46b[i] = '.'47case UniqueX:48b[i] = 'X'49case UniqueY:50b[i] = 'Y'51case Modified:52b[i] = 'M'53default:54panic("invalid edit-type")55}56}57return string(b)58}5960// stats returns a histogram of the number of each type of edit operation.61func (es EditScript) stats() (s struct{ NI, NX, NY, NM int }) {62for _, e := range es {63switch e {64case Identity:65s.NI++66case UniqueX:67s.NX++68case UniqueY:69s.NY++70case Modified:71s.NM++72default:73panic("invalid edit-type")74}75}76return77}7879// Dist is the Levenshtein distance and is guaranteed to be 0 if and only if80// lists X and Y are equal.81func (es EditScript) Dist() int { return len(es) - es.stats().NI }8283// LenX is the length of the X list.84func (es EditScript) LenX() int { return len(es) - es.stats().NY }8586// LenY is the length of the Y list.87func (es EditScript) LenY() int { return len(es) - es.stats().NX }8889// EqualFunc reports whether the symbols at indexes ix and iy are equal.90// When called by Difference, the index is guaranteed to be within nx and ny.91type EqualFunc func(ix int, iy int) Result9293// Result is the result of comparison.94// NumSame is the number of sub-elements that are equal.95// NumDiff is the number of sub-elements that are not equal.96type Result struct{ NumSame, NumDiff int }9798// BoolResult returns a Result that is either Equal or not Equal.99func BoolResult(b bool) Result {100if b {101return Result{NumSame: 1} // Equal, Similar102} else {103return Result{NumDiff: 2} // Not Equal, not Similar104}105}106107// Equal indicates whether the symbols are equal. Two symbols are equal108// if and only if NumDiff == 0. If Equal, then they are also Similar.109func (r Result) Equal() bool { return r.NumDiff == 0 }110111// Similar indicates whether two symbols are similar and may be represented112// by using the Modified type. As a special case, we consider binary comparisons113// (i.e., those that return Result{1, 0} or Result{0, 1}) to be similar.114//115// The exact ratio of NumSame to NumDiff to determine similarity may change.116func (r Result) Similar() bool {117// Use NumSame+1 to offset NumSame so that binary comparisons are similar.118return r.NumSame+1 >= r.NumDiff119}120121var randBool = rand.New(rand.NewSource(time.Now().Unix())).Intn(2) == 0122123// Difference reports whether two lists of lengths nx and ny are equal124// given the definition of equality provided as f.125//126// This function returns an edit-script, which is a sequence of operations127// needed to convert one list into the other. The following invariants for128// the edit-script are maintained:129// - eq == (es.Dist()==0)130// - nx == es.LenX()131// - ny == es.LenY()132//133// This algorithm is not guaranteed to be an optimal solution (i.e., one that134// produces an edit-script with a minimal Levenshtein distance). This algorithm135// favors performance over optimality. The exact output is not guaranteed to136// be stable and may change over time.137func Difference(nx, ny int, f EqualFunc) (es EditScript) {138// This algorithm is based on traversing what is known as an "edit-graph".139// See Figure 1 from "An O(ND) Difference Algorithm and Its Variations"140// by Eugene W. Myers. Since D can be as large as N itself, this is141// effectively O(N^2). Unlike the algorithm from that paper, we are not142// interested in the optimal path, but at least some "decent" path.143//144// For example, let X and Y be lists of symbols:145// X = [A B C A B B A]146// Y = [C B A B A C]147//148// The edit-graph can be drawn as the following:149// A B C A B B A150// ┌─────────────┐151// C │_|_|\|_|_|_|_│ 0152// B │_|\|_|_|\|\|_│ 1153// A │\|_|_|\|_|_|\│ 2154// B │_|\|_|_|\|\|_│ 3155// A │\|_|_|\|_|_|\│ 4156// C │ | |\| | | | │ 5157// └─────────────┘ 6158// 0 1 2 3 4 5 6 7159//160// List X is written along the horizontal axis, while list Y is written161// along the vertical axis. At any point on this grid, if the symbol in162// list X matches the corresponding symbol in list Y, then a '\' is drawn.163// The goal of any minimal edit-script algorithm is to find a path from the164// top-left corner to the bottom-right corner, while traveling through the165// fewest horizontal or vertical edges.166// A horizontal edge is equivalent to inserting a symbol from list X.167// A vertical edge is equivalent to inserting a symbol from list Y.168// A diagonal edge is equivalent to a matching symbol between both X and Y.169170// Invariants:171// - 0 ≤ fwdPath.X ≤ (fwdFrontier.X, revFrontier.X) ≤ revPath.X ≤ nx172// - 0 ≤ fwdPath.Y ≤ (fwdFrontier.Y, revFrontier.Y) ≤ revPath.Y ≤ ny173//174// In general:175// - fwdFrontier.X < revFrontier.X176// - fwdFrontier.Y < revFrontier.Y177//178// Unless, it is time for the algorithm to terminate.179fwdPath := path{+1, point{0, 0}, make(EditScript, 0, (nx+ny)/2)}180revPath := path{-1, point{nx, ny}, make(EditScript, 0)}181fwdFrontier := fwdPath.point // Forward search frontier182revFrontier := revPath.point // Reverse search frontier183184// Search budget bounds the cost of searching for better paths.185// The longest sequence of non-matching symbols that can be tolerated is186// approximately the square-root of the search budget.187searchBudget := 4 * (nx + ny) // O(n)188189// Running the tests with the "cmp_debug" build tag prints a visualization190// of the algorithm running in real-time. This is educational for191// understanding how the algorithm works. See debug_enable.go.192f = debug.Begin(nx, ny, f, &fwdPath.es, &revPath.es)193194// The algorithm below is a greedy, meet-in-the-middle algorithm for195// computing sub-optimal edit-scripts between two lists.196//197// The algorithm is approximately as follows:198// - Searching for differences switches back-and-forth between199// a search that starts at the beginning (the top-left corner), and200// a search that starts at the end (the bottom-right corner).201// The goal of the search is connect with the search202// from the opposite corner.203// - As we search, we build a path in a greedy manner,204// where the first match seen is added to the path (this is sub-optimal,205// but provides a decent result in practice). When matches are found,206// we try the next pair of symbols in the lists and follow all matches207// as far as possible.208// - When searching for matches, we search along a diagonal going through209// through the "frontier" point. If no matches are found,210// we advance the frontier towards the opposite corner.211// - This algorithm terminates when either the X coordinates or the212// Y coordinates of the forward and reverse frontier points ever intersect.213214// This algorithm is correct even if searching only in the forward direction215// or in the reverse direction. We do both because it is commonly observed216// that two lists commonly differ because elements were added to the front217// or end of the other list.218//219// Non-deterministically start with either the forward or reverse direction220// to introduce some deliberate instability so that we have the flexibility221// to change this algorithm in the future.222if flags.Deterministic || randBool {223goto forwardSearch224} else {225goto reverseSearch226}227228forwardSearch:229{230// Forward search from the beginning.231if fwdFrontier.X >= revFrontier.X || fwdFrontier.Y >= revFrontier.Y || searchBudget == 0 {232goto finishSearch233}234for stop1, stop2, i := false, false, 0; !(stop1 && stop2) && searchBudget > 0; i++ {235// Search in a diagonal pattern for a match.236z := zigzag(i)237p := point{fwdFrontier.X + z, fwdFrontier.Y - z}238switch {239case p.X >= revPath.X || p.Y < fwdPath.Y:240stop1 = true // Hit top-right corner241case p.Y >= revPath.Y || p.X < fwdPath.X:242stop2 = true // Hit bottom-left corner243case f(p.X, p.Y).Equal():244// Match found, so connect the path to this point.245fwdPath.connect(p, f)246fwdPath.append(Identity)247// Follow sequence of matches as far as possible.248for fwdPath.X < revPath.X && fwdPath.Y < revPath.Y {249if !f(fwdPath.X, fwdPath.Y).Equal() {250break251}252fwdPath.append(Identity)253}254fwdFrontier = fwdPath.point255stop1, stop2 = true, true256default:257searchBudget-- // Match not found258}259debug.Update()260}261// Advance the frontier towards reverse point.262if revPath.X-fwdFrontier.X >= revPath.Y-fwdFrontier.Y {263fwdFrontier.X++264} else {265fwdFrontier.Y++266}267goto reverseSearch268}269270reverseSearch:271{272// Reverse search from the end.273if fwdFrontier.X >= revFrontier.X || fwdFrontier.Y >= revFrontier.Y || searchBudget == 0 {274goto finishSearch275}276for stop1, stop2, i := false, false, 0; !(stop1 && stop2) && searchBudget > 0; i++ {277// Search in a diagonal pattern for a match.278z := zigzag(i)279p := point{revFrontier.X - z, revFrontier.Y + z}280switch {281case fwdPath.X >= p.X || revPath.Y < p.Y:282stop1 = true // Hit bottom-left corner283case fwdPath.Y >= p.Y || revPath.X < p.X:284stop2 = true // Hit top-right corner285case f(p.X-1, p.Y-1).Equal():286// Match found, so connect the path to this point.287revPath.connect(p, f)288revPath.append(Identity)289// Follow sequence of matches as far as possible.290for fwdPath.X < revPath.X && fwdPath.Y < revPath.Y {291if !f(revPath.X-1, revPath.Y-1).Equal() {292break293}294revPath.append(Identity)295}296revFrontier = revPath.point297stop1, stop2 = true, true298default:299searchBudget-- // Match not found300}301debug.Update()302}303// Advance the frontier towards forward point.304if revFrontier.X-fwdPath.X >= revFrontier.Y-fwdPath.Y {305revFrontier.X--306} else {307revFrontier.Y--308}309goto forwardSearch310}311312finishSearch:313// Join the forward and reverse paths and then append the reverse path.314fwdPath.connect(revPath.point, f)315for i := len(revPath.es) - 1; i >= 0; i-- {316t := revPath.es[i]317revPath.es = revPath.es[:i]318fwdPath.append(t)319}320debug.Finish()321return fwdPath.es322}323324type path struct {325dir int // +1 if forward, -1 if reverse326point // Leading point of the EditScript path327es EditScript328}329330// connect appends any necessary Identity, Modified, UniqueX, or UniqueY types331// to the edit-script to connect p.point to dst.332func (p *path) connect(dst point, f EqualFunc) {333if p.dir > 0 {334// Connect in forward direction.335for dst.X > p.X && dst.Y > p.Y {336switch r := f(p.X, p.Y); {337case r.Equal():338p.append(Identity)339case r.Similar():340p.append(Modified)341case dst.X-p.X >= dst.Y-p.Y:342p.append(UniqueX)343default:344p.append(UniqueY)345}346}347for dst.X > p.X {348p.append(UniqueX)349}350for dst.Y > p.Y {351p.append(UniqueY)352}353} else {354// Connect in reverse direction.355for p.X > dst.X && p.Y > dst.Y {356switch r := f(p.X-1, p.Y-1); {357case r.Equal():358p.append(Identity)359case r.Similar():360p.append(Modified)361case p.Y-dst.Y >= p.X-dst.X:362p.append(UniqueY)363default:364p.append(UniqueX)365}366}367for p.X > dst.X {368p.append(UniqueX)369}370for p.Y > dst.Y {371p.append(UniqueY)372}373}374}375376func (p *path) append(t EditType) {377p.es = append(p.es, t)378switch t {379case Identity, Modified:380p.add(p.dir, p.dir)381case UniqueX:382p.add(p.dir, 0)383case UniqueY:384p.add(0, p.dir)385}386debug.Update()387}388389type point struct{ X, Y int }390391func (p *point) add(dx, dy int) { p.X += dx; p.Y += dy }392393// zigzag maps a consecutive sequence of integers to a zig-zag sequence.394//395// [0 1 2 3 4 5 ...] => [0 -1 +1 -2 +2 ...]396func zigzag(x int) int {397if x&1 != 0 {398x = ^x399}400return x >> 1401}402403404