all repos

clerk @ 17c786e

missing tooling for ledger/hledger

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

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