Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion diff/diff.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ func (d *Diff) SideAt(x int) (s Side, onNumber bool) {
func Count(old, new string) (added, deleted int) {
old = strings.ReplaceAll(old, "\r\n", "\n")
new = strings.ReplaceAll(new, "\r\n", "\n")
u, err := udiff.ToUnifiedDiff("", "", old, udiff.Lines(old, new), 0)
u, err := udiff.ToUnifiedDiff("", "", old, diffview.Edits(old, new), 0)
if err != nil {
return 0, 0
}
Expand Down
51 changes: 50 additions & 1 deletion internal/diffview/diffview.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (

"charm.land/lipgloss/v2"
"github.com/aymanbagabas/go-udiff"
"github.com/aymanbagabas/go-udiff/lcs"
"github.com/charmbracelet/x/ansi"
)

Expand Down Expand Up @@ -123,7 +124,7 @@ func Render(path, before, after string, o Options) ([]string, []Row, Geometry) {
// diffHunks computes the hunks of the diff, with the tabs of the lines
// replaced after the diff, so that a change from a tab to spaces shows.
func diffHunks(before, after string, tabWidth, context int) []hunk {
u, err := udiff.ToUnifiedDiff("", "", before, udiff.Lines(before, after), context)
u, err := udiff.ToUnifiedDiff("", "", before, Edits(before, after), context)
if err != nil {
return nil
}
Expand Down Expand Up @@ -168,6 +169,54 @@ func diffHunks(before, after string, tabWidth, context int) []hunk {
return hunks
}

// Edits returns the line edits that change before into after. They are
// the same as the edits of udiff.Lines, but Edits takes less time on a
// large file, in the way of @pierre/patches: it finds the line ends with
// strings.IndexByte instead of decoding each rune, it diffs integer ids of
// the lines instead of the lines, and the new text of an edit is a slice
// of after instead of a copy.
func Edits(before, after string) []udiff.Edit {
ids := make(map[string]rune)
a, aOffsets := lineIDs(before, ids)
b, bOffsets := lineIDs(after, ids)
// The lcs package compares only for equality, and two lines have the
// same id only if they are equal, so the runes give the same diff as
// the lines.
diffs := lcs.DiffRunes(a, b)
edits := make([]udiff.Edit, len(diffs))
for i, d := range diffs {
edits[i] = udiff.Edit{
Start: aOffsets[d.Start],
End: aOffsets[d.End],
New: after[bOffsets[d.ReplStart]:bOffsets[d.ReplEnd]],
}
}
return edits
}

// lineIDs splits s into lines, each with its LF, and returns the id of
// each line from ids, which it adds new lines to. The offsets are the
// start of each line and then the end of s.
func lineIDs(s string, ids map[string]rune) (lines []rune, offsets []int) {
n := strings.Count(s, "\n") + 1
lines, offsets = make([]rune, 0, n), make([]int, 1, n+1)
for start := 0; start < len(s); {
end := len(s)
if i := strings.IndexByte(s[start:], '\n'); i >= 0 {
end = start + i + 1
}
id, ok := ids[s[start:end]]
if !ok {
id = rune(len(ids))
ids[s[start:end]] = id
}
lines = append(lines, id)
offsets = append(offsets, end)
start = end
}
return lines, offsets
}

// pairs puts the lines of a hunk side by side. An equal line is on both
// sides. In each run of changed lines, the n-th deleted line is beside the
// n-th inserted line. A nil side has no line.
Expand Down
76 changes: 76 additions & 0 deletions internal/diffview/edits_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package diffview

import (
"fmt"
"math/rand/v2"
"reflect"
"strings"
"testing"

"github.com/aymanbagabas/go-udiff"
)

// TestEditsMatchUdiff checks that Edits gives the same edits as
// udiff.Lines, which it replaces. The lines come from a few values, so
// that many of them repeat.
func TestEditsMatchUdiff(t *testing.T) {
values := []string{"", "a", "b", "}", "\tx := 1", "\r", "\xe2", "é"}
text := func(r *rand.Rand) string {
var b strings.Builder
for range r.IntN(30) {
b.WriteString(values[r.IntN(len(values))] + "\n")
}
if r.IntN(2) == 0 { // a last line without LF
b.WriteString(values[r.IntN(len(values))])
}
return b.String()
}
r := rand.New(rand.NewPCG(1, 2))
for range 10_000 {
before, after := text(r), text(r)
if got, want := Edits(before, after), udiff.Lines(before, after); !reflect.DeepEqual(got, want) {
t.Fatalf("Edits(%q, %q)\n got %v\nwant %v", before, after, got, want)
}
}
}

// BenchmarkDiffHunks diffs two versions of a file of 100,000 lines, as
// Render does before it draws them:
//
// go test ./internal/diffview -run '^$' -bench DiffHunks -count 10
func BenchmarkDiffHunks(b *testing.B) {
const n = 100_000
lines := make([]string, n)
for i := range lines {
switch i % 10 {
case 0:
lines[i] = "}"
case 1:
lines[i] = ""
default:
lines[i] = fmt.Sprintf("\tx%d := compute(%q, %d) // a line of a large file", i, strings.Repeat("a", i%40), i)
}
}
before := strings.Join(lines, "\n") + "\n"

// Edits changes one line in every 2,000.
edited := append([]string(nil), lines...)
for i := 1000; i < n; i += 2000 {
edited[i] += " // changed"
}
// Insert adds a block of 2,000 lines in the middle.
inserted := append(append(append([]string(nil), lines[:n/2]...), lines[:2000]...), lines[n/2:]...)

for _, c := range []struct{ name, after string }{
{"edits", strings.Join(edited, "\n") + "\n"},
{"insert", strings.Join(inserted, "\n") + "\n"},
} {
b.Run(c.name, func(b *testing.B) {
b.SetBytes(int64(len(before) + len(c.after)))
b.ReportAllocs()
for b.Loop() {
diffHunks(before, c.after, 8, 3)
}
})
}
}
65 changes: 59 additions & 6 deletions internal/diffview/scope.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,66 @@
package diffview

import (
"regexp"
"strings"
)

// declaration matches a line that declares a function, a type, or a
// module in most languages, after optional modifiers such as "pub".
var declaration = regexp.MustCompile(`^\s*(?:(?:export|pub(?:\([a-z]+\))?|public|private|protected|internal|static|async|abstract|final|sealed|open|override|default|unsafe|inline|virtual|extern|data|const)\s+)*(?:def|class|func|fn|fun|function|struct|enum|union|trait|impl|interface|type|module|mod|namespace|object|record|protocol|extension|actor|macro|sub|proc)\b`)
// The words that start a declaration of a function, a type, or a module in
// most languages, and the modifiers that can come before them.
var (
keywords = wordSet("def class func fn fun function struct enum union trait impl interface type module mod namespace object record protocol extension actor macro sub proc")
modifiers = wordSet("export pub public private protected internal static async abstract final sealed open override default unsafe inline virtual extern data const")
)

func wordSet(s string) map[string]bool {
set := map[string]bool{}
for _, w := range strings.Fields(s) {
set[w] = true
}
return set
}

// space is the set of \s in a regular expression.
const space = " \t\n\f\r"

// isDeclaration reports whether l declares a function, a type, or a
// module: after indent and modifiers such as "pub" or "pub(crate)", the
// first word is a keyword such as "func". It matches the same lines as
// the regular expression
//
// ^\s*(?:(?:modifier|pub\([a-z]+\))\s+)*keyword\b
//
// but scopesOf calls it on each line of a file, and the regular expression
// took most of the time of a large diff.
func isDeclaration(l string) bool {
s := strings.TrimLeft(l, space)
for {
n := 0
for n < len(s) && isWordByte(s[n]) {
n++
}
w, rest := s[:n], s[n:]
if keywords[w] {
return true
}
if !modifiers[w] {
return false
}
if w == "pub" && strings.HasPrefix(rest, "(") {
if i := strings.IndexByte(rest, ')'); i > 1 && strings.Trim(rest[1:i], "abcdefghijklmnopqrstuvwxyz") == "" {
rest = rest[i+1:]
}
}
s = strings.TrimLeft(rest, space)
if len(s) == len(rest) { // a modifier needs space after it
return false
}
}
}

// isWordByte reports whether b is in \w, the bytes of a word.
func isWordByte(b byte) bool {
return b == '_' || '0' <= b && b <= '9' || 'a' <= b|0x20 && b|0x20 <= 'z'
}

// scopesOf returns the scope of each line in firsts (0-based, ascending):
// the line that encloses it, as "def foo(" or "func (v *View) text() string {",
Expand All @@ -33,8 +86,8 @@ func scopesOf(lines []string, firsts []int) []string {
}
d := indent(l)
c := l[d]
if declaration.MatchString(l) ||
d == 0 && (c == '_' || c == '$' || 'a' <= c|0x20 && c|0x20 <= 'z') {
if d == 0 && (c == '_' || c == '$' || 'a' <= c|0x20 && c|0x20 <= 'z') ||
isDeclaration(l) {
for len(stack) > 0 && stack[len(stack)-1].indent >= d {
stack = stack[:len(stack)-1]
}
Expand Down
25 changes: 25 additions & 0 deletions internal/diffview/scope_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package diffview

import (
"math/rand/v2"
"regexp"
"strings"
"testing"
)
Expand Down Expand Up @@ -31,3 +33,26 @@ func TestScopesOfMany(t *testing.T) {
t.Errorf("got %q, want %q", got, want)
}
}

// TestIsDeclarationMatchesRegexp checks that isDeclaration matches the
// same lines as the regular expression it replaces. The lines join
// random pieces of declarations, words, and spaces.
func TestIsDeclarationMatchesRegexp(t *testing.T) {
declaration := regexp.MustCompile(`^\s*(?:(?:export|pub(?:\([a-z]+\))?|public|private|protected|internal|static|async|abstract|final|sealed|open|override|default|unsafe|inline|virtual|extern|data|const)\s+)*(?:def|class|func|fn|fun|function|struct|enum|union|trait|impl|interface|type|module|mod|namespace|object|record|protocol|extension|actor|macro|sub|proc)\b`)
pieces := []string{
"func", "fn", "def", "class", "define", "Func", "fn_", "func2", "funcé",
"pub", "pub(crate)", "pub(Crate)", "pub()", "pub(", ")", "public", "static", "async",
" ", " ", "\t", "\v", "\f", "\r", "x", "_", "é", "(", ":", "{", "$",
}
r := rand.New(rand.NewPCG(3, 4))
for range 200_000 {
var b strings.Builder
for range r.IntN(6) {
b.WriteString(pieces[r.IntN(len(pieces))])
}
l := b.String()
if got, want := isDeclaration(l), declaration.MatchString(l); got != want {
t.Fatalf("isDeclaration(%q) = %v, want %v", l, got, want)
}
}
}
Loading