all repos

clerk @ c958816

missing tooling for ledger/hledger

clerk/internal/lsp/textdocument_completion_test.go (view raw)

Oleksandr Smirnov Oleksandr Smirnov
olexsmir@gmail.com
lsp: go to definition on include file path, 1 month ago
1
package lsp
2
3
import (
4
	"fmt"
5
	"strings"
6
	"testing"
7
	"time"
8
9
	"go.lsp.dev/protocol"
10
	"go.lsp.dev/uri"
11
12
	"olexsmir.xyz/clerk/internal/lsp/lsputil"
13
	"olexsmir.xyz/clerk/internal/testutil/golden"
14
	"olexsmir.xyz/clerk/journal"
15
)
16
17
func TestDetectCompletion_NoJournal(t *testing.T) {
18
	// detection must not depend on a parse
19
	i := strings.Index("    no^te foo\n", "^")
20
	content := "    note foo\n"
21
	ctx, _ := detectCompletionCtx(content, i)
22
	if ctx != cmplAccount {
23
		t.Errorf("ctx = %v, want account", ctx)
24
	}
25
}
26
27
func TestDateStyle(t *testing.T) {
28
	tests := map[string]struct {
29
		history []string
30
		sep     byte
31
		hasYear bool
32
	}{
33
		"empty":    {nil, '-', true},
34
		"dash":     {[]string{"2024-01-02"}, '-', true},
35
		"slash":    {[]string{"2024/01/20"}, '/', true},
36
		"yearless": {[]string{"6-10"}, '-', false},
37
	}
38
	for name, tt := range tests {
39
		t.Run(name, func(t *testing.T) {
40
			sep, hasYear := dateStyle(tt.history)
41
			if sep != tt.sep || hasYear != tt.hasYear {
42
				t.Errorf("dateStyle = %q/%v, want %q/%v", sep, hasYear, tt.sep, tt.hasYear)
43
			}
44
		})
45
	}
46
}
47
48
func TestDateTokenEnd(t *testing.T) {
49
	tests := map[string]struct {
50
		content string
51
		start   int
52
		want    int
53
	}{
54
		"full date":            {"2024-01-02 x", 0, 10},
55
		"unpadded":             {"2024/1/2 x", 0, 8},
56
		"yearless":             {"6-10 x", 0, 4},
57
		"stops at =":           {"2024-01-02=2024-01-03", 0, 10},
58
		"stops at comment":     {"2024-01-02;x", 0, 10},
59
		"partial trailing sep": {"2024- x", 0, 5},
60
		"partial mid":          {"2024-0 x", 0, 6},
61
	}
62
	for name, tt := range tests {
63
		t.Run(name, func(t *testing.T) {
64
			if got := dateTokenEnd(tt.content, tt.start); got != tt.want {
65
				t.Errorf("dateTokenEnd = %d, want %d", got, tt.want)
66
			}
67
		})
68
	}
69
}
70
71
func TestDatePatternMatch(t *testing.T) {
72
	tests := map[string]struct {
73
		pattern, canonical string
74
		want               bool
75
	}{
76
		"digit subsequence":   {"2024-01-0", "2024-01-05", true},
77
		"same sep":            {"2024/0", "2024/01/20", true},
78
		"other sep rejected":  {"2024/0", "2024-01-20", false},
79
		"yearless":            {"6-10", "6-10", true},
80
		"yearless padded rej": {"06-10", "6-10", false},
81
		"no match":            {"2025", "2024-01-20", false},
82
		"empty":               {"", "2024-01-20", true},
83
	}
84
	for name, tt := range tests {
85
		t.Run(name, func(t *testing.T) {
86
			if got := datePatternMatch(tt.pattern, tt.canonical); got != tt.want {
87
				t.Errorf("datePatternMatch = %v, want %v", got, tt.want)
88
			}
89
		})
90
	}
91
}
92
93
func TestGolden_Completion(t *testing.T) {
94
	for _, tt := range []string{"completion-contexts", "completion-journal", "completion-no-transactions"} {
95
		t.Run(tt, func(t *testing.T) {
96
			ar := golden.Read(t, tt)
97
			h := newTxtarHarness(t, ar)
98
			if err := h.srv.applySettings(t.Context(), []byte(`{"latin_to_cyrillic_completion": true}`)); err != nil {
99
				t.Fatal(err)
100
			}
101
102
			var b strings.Builder
103
			for i, c := range h.cursors {
104
				tdp := h.textDocumentPosition(i)
105
				res, err := h.srv.Completion(t.Context(), &protocol.CompletionParams{
106
					TextDocumentPositionParams: tdp,
107
				})
108
				if err != nil {
109
					t.Fatal(err)
110
				}
111
				ctx, start := detectCompletionCtx(h.content, c)
112
				fmt.Fprintf(&b, "%d:%d %s %q\n", tdp.Position.Line, tdp.Position.Character, ctx, h.content[start:c])
113
				list, ok := res.(*protocol.CompletionList)
114
				if !ok {
115
					t.Fatalf("Completion returned %T, want *protocol.CompletionList", res)
116
				}
117
				now := time.Now()
118
				var sep byte
119
				var hasYear bool
120
				if ctx == cmplDate {
121
					if an := h.srv.analysisFor(h.uri); an != nil {
122
						sep, hasYear = dateStyle(an.DateStrings)
123
					}
124
				}
125
				for _, item := range list.Items {
126
					label := item.Label
127
					if ctx == cmplDate {
128
						switch label {
129
						case renderDate(now, sep, hasYear):
130
							label = "today"
131
						case renderDate(now.AddDate(0, 0, -1), sep, hasYear):
132
							label = "yesterday"
133
						case renderDate(now.AddDate(0, 0, -2), sep, hasYear):
134
							label = "2 days ago"
135
						}
136
					}
137
					fmt.Fprintf(&b, "  %s\n", label)
138
				}
139
			}
140
			golden.Assert(t, ar, b.String())
141
		})
142
	}
143
}
144
145
func (c cmplCtx) String() string {
146
	switch c {
147
	case cmplNone:
148
		return "none"
149
	case cmplAccount:
150
		return "account"
151
	case cmplPayee:
152
		return "payee"
153
	case cmplCommodity:
154
		return "commodity"
155
	case cmplTagName:
156
		return "tag"
157
	case cmplTagValue:
158
		return "tag-value"
159
	case cmplDate:
160
		return "date"
161
	case cmplDirective:
162
		return "directive"
163
	default:
164
		return "?"
165
	}
166
}
167
168
func BenchmarkCompletion(b *testing.B) {
169
	path := "../../journal/testdata/journals/actual-1ktxns-100accts.journal"
170
	rj, err := journal.NewLoader().Resolve(path)
171
	if err != nil {
172
		b.Fatal(err)
173
	}
174
	content := string(rj.Occurrences[0].Src)
175
176
	srv := newServer(b)
177
	srv.server.openDoc(uri.URI("file:///test.journal"), content, 1, "journal")
178
	srv.server.analysisFor(uri.URI("file:///test.journal")) // warm the per-doc cache
179
180
	for tname, tt := range map[string]int{
181
		"1k txns, account":        strings.Index(content, "\n  1:2:3 ") + len("\n  ") + 2,
182
		"1k txns, empty payee":    strings.Index(content, "transaction 1") + len("transaction "),
183
		"1k txns, commodity":      strings.Index(content, "2 B @@") + len("2 B"),
184
		"1k txns, date":           strings.Index(content, "2000-01-0") + len("2000-01-0"),
185
		"1k txns, price date":     strings.Index(content, "P 2000-01-0") + len("P 2000-01-0"),
186
		"1k txns, price quantity": strings.Index(content, "P 2000-01-01 A  0.70") + len("P 2000-01-01 A  0.70"),
187
	} {
188
		b.Run(tname, func(b *testing.B) {
189
			line, col := lsputil.LineCol(content, tt)
190
			params := &protocol.CompletionParams{
191
				TextDocument: protocol.TextDocumentIdentifier{URI: uri.URI("file:///test.journal")},
192
				Position:     protocol.Position{Line: uint32(line), Character: uint32(col)},
193
			}
194
195
			// warm up
196
			if _, err := srv.server.Completion(b.Context(), params); err != nil {
197
				b.Fatal(err)
198
			}
199
			b.ReportAllocs()
200
			b.ResetTimer()
201
			for b.Loop() {
202
				if _, err := srv.server.Completion(b.Context(), params); err != nil {
203
					b.Fatal(err)
204
				}
205
			}
206
			// guard: line-local lexing must stay far below the old whole-file
207
			// relex (~3ms on this file); the measured target is sub-ms
208
			if avg := b.Elapsed() / time.Duration(b.N); avg > 2*time.Millisecond {
209
				b.Fatalf("completion %v/op: whole-file relex regression", avg)
210
			}
211
		})
212
	}
213
}
214
215
func BenchmarkCompletionTransliteration(b *testing.B) {
216
	tails := []string{"а", "б", "в", "г", "д", "е", "є", "ж", "з", "и", "і", "ї", "й", "к", "л", "м", "н", "о", "п", "р"}
217
	var sb strings.Builder
218
	for _, n := range []string{"Витрати", "Доходи", "Активи", "Капітал", "Зобовязання"} {
219
		for _, t := range tails {
220
			fmt.Fprintf(&sb, "account %s:%s%s\n", n, n, t)
221
		}
222
	}
223
	sb.WriteString("account vyt")
224
	content := sb.String()
225
226
	srv := newServer(b)
227
	srv.server.openDoc(uri.URI("file:///test.journal"), content, 1, "journal")
228
	srv.server.analysisFor(uri.URI("file:///test.journal")) // warm the per-doc cache
229
	if err := srv.server.applySettings(b.Context(), []byte(`{"latin_to_cyrillic_completion": true}`)); err != nil {
230
		b.Fatal(err)
231
	}
232
233
	line, col := lsputil.LineCol(content, len(content))
234
	params := &protocol.CompletionParams{
235
		TextDocument: protocol.TextDocumentIdentifier{URI: uri.URI("file:///test.journal")},
236
		Position:     protocol.Position{Line: uint32(line), Character: uint32(col)},
237
	}
238
239
	warm, err := srv.server.Completion(b.Context(), params)
240
	if err != nil {
241
		b.Fatal(err)
242
	}
243
244
	// Guard: the Cyrillic corpus completes only through the transliterated
245
	// pattern; without it the list collapses to the latin "vyt" placeholder.
246
	if got := len(warm.(*protocol.CompletionList).Items); got <= 1 {
247
		b.Fatalf("transliteration matching did not engage (items: %d)", got)
248
	}
249
250
	b.ReportAllocs()
251
	b.ResetTimer()
252
	for b.Loop() {
253
		if _, err := srv.server.Completion(b.Context(), params); err != nil {
254
			b.Fatal(err)
255
		}
256
	}
257
}