gitstack

grindlemire/go-tui code browser

11.5 KB Go 475 lines 2026-06-03 · d15bb9f raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
package provider

import (
	"testing"
)

// stubFnChecker implements FunctionNameChecker for testing.
type stubFnChecker struct {
	names map[string]bool
}

func (s *stubFnChecker) IsFunctionName(name string) bool {
	return s.names[name]
}

func newTestSemanticProvider() *semanticTokensProvider {
	return &semanticTokensProvider{
		fnChecker: &stubFnChecker{names: map[string]bool{
			"Sprintf": true,
			"len":     true,
		}},
	}
}

// decodeTokens decodes LSP delta-encoded semantic token data into absolute positions.
func decodeTokens(data []int) []SemanticToken {
	var tokens []SemanticToken
	prevLine := 0
	prevChar := 0

	for i := 0; i+4 < len(data); i += 5 {
		deltaLine := data[i]
		deltaChar := data[i+1]
		length := data[i+2]
		tokenType := data[i+3]
		modifiers := data[i+4]

		line := prevLine + deltaLine
		startChar := deltaChar
		if deltaLine == 0 {
			startChar = prevChar + deltaChar
		}

		tokens = append(tokens, SemanticToken{
			Line:      line,
			StartChar: startChar,
			Length:    length,
			TokenType: tokenType,
			Modifiers: modifiers,
		})

		prevLine = line
		prevChar = startChar
	}

	return tokens
}

// countByType counts tokens of a given type in decoded tokens.
func countByType(tokens []SemanticToken, tokenType int) int {
	count := 0
	for _, t := range tokens {
		if t.TokenType == tokenType {
			count++
		}
	}
	return count
}

// hasTokenAt checks if a token exists at the given position with the given type and length.
func hasTokenAt(tokens []SemanticToken, line, col, length, tokenType int) bool {
	for _, tok := range tokens {
		if tok.Line == line && tok.StartChar == col && tok.Length == length && tok.TokenType == tokenType {
			return true
		}
	}
	return false
}

func TestSemanticTokens_ComponentDecl(t *testing.T) {
	type tc struct {
		content       string
		wantKeyword   bool // should find "templ" keyword token
		wantClassName bool // should find component name token
		wantParams    int  // number of parameter tokens expected
	}

	tests := map[string]tc{
		"simple component": {
			content: `package main

templ Hello() {
	<span>Hello</span>
}
`,
			wantKeyword:   true,
			wantClassName: true,
			wantParams:    0,
		},
		"component with params": {
			content: `package main

templ Greeting(name string, count int) {
	<span>{name}</span>
}
`,
			wantKeyword:   true,
			wantClassName: true,
			wantParams:    2,
		},
	}

	sp := newTestSemanticProvider()

	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			doc := parseTestDoc(tt.content)
			result, err := sp.SemanticTokensFull(doc)
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}

			tokens := decodeTokens(result.Data)

			keywordCount := countByType(tokens, TokenTypeKeyword)
			if tt.wantKeyword && keywordCount == 0 {
				t.Error("expected at least one keyword token (templ)")
			}

			classCount := countByType(tokens, TokenTypeClass)
			if tt.wantClassName && classCount == 0 {
				t.Error("expected at least one class token (component name)")
			}

			paramCount := countByType(tokens, TokenTypeParameter)
			if paramCount < tt.wantParams {
				t.Errorf("got %d parameter tokens, want at least %d", paramCount, tt.wantParams)
			}
		})
	}

	// Position assertions for "simple component": templ keyword at line 2, col 0
	t.Run("simple component positions", func(t *testing.T) {
		doc := parseTestDoc(tests["simple component"].content)
		result, err := sp.SemanticTokensFull(doc)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		tokens := decodeTokens(result.Data)

		if !hasTokenAt(tokens, 2, 0, 5, TokenTypeKeyword) {
			t.Error("expected templ keyword token at 2:0 with length 5")
		}
		if !hasTokenAt(tokens, 2, 6, 5, TokenTypeClass) {
			t.Error("expected Hello class token at 2:6 with length 5")
		}
	})

	// Position assertions for "component with params": params at expected positions
	t.Run("component with params positions", func(t *testing.T) {
		doc := parseTestDoc(tests["component with params"].content)
		result, err := sp.SemanticTokensFull(doc)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		tokens := decodeTokens(result.Data)

		if !hasTokenAt(tokens, 2, 0, 5, TokenTypeKeyword) {
			t.Error("expected templ keyword token at 2:0 with length 5")
		}
		if !hasTokenAt(tokens, 2, 6, 8, TokenTypeClass) {
			t.Error("expected Greeting class token at 2:6 with length 8")
		}
	})
}

func TestSemanticTokens_FunctionDecl(t *testing.T) {
	type tc struct {
		content  string
		wantFunc bool
	}

	tests := map[string]tc{
		"helper function": {
			content: `package main

func helper(s string) string {
	return s
}
`,
			wantFunc: true,
		},
	}

	sp := newTestSemanticProvider()

	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			doc := parseTestDoc(tt.content)
			result, err := sp.SemanticTokensFull(doc)
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}

			tokens := decodeTokens(result.Data)

			funcCount := countByType(tokens, TokenTypeFunction)
			if tt.wantFunc && funcCount == 0 {
				t.Error("expected at least one function token")
			}
		})
	}
}

func TestSemanticTokens_Keywords(t *testing.T) {
	type tc struct {
		content     string
		wantKeyword int // minimum number of keyword tokens
	}

	tests := map[string]tc{
		"for loop keyword": {
			content: `package main

templ List(items []string) {
	for _, item := range items {
		<span>{item}</span>
	}
}
`,
			wantKeyword: 2, // templ + for
		},
		"if/else keywords": {
			content: `package main

templ Cond(show bool) {
	if show {
		<span>Yes</span>
	} else {
		<span>No</span>
	}
}
`,
			wantKeyword: 2, // templ + if (at minimum)
		},
	}

	sp := newTestSemanticProvider()

	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			doc := parseTestDoc(tt.content)
			result, err := sp.SemanticTokensFull(doc)
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}

			tokens := decodeTokens(result.Data)

			keywordCount := countByType(tokens, TokenTypeKeyword)
			if keywordCount < tt.wantKeyword {
				t.Errorf("got %d keyword tokens, want at least %d", keywordCount, tt.wantKeyword)
			}
		})
	}

	// Position assertions for "for loop keyword"
	t.Run("for loop keyword positions", func(t *testing.T) {
		doc := parseTestDoc(tests["for loop keyword"].content)
		result, err := sp.SemanticTokensFull(doc)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		tokens := decodeTokens(result.Data)

		if !hasTokenAt(tokens, 2, 0, 5, TokenTypeKeyword) {
			t.Error("expected templ keyword at 2:0 with length 5")
		}
		if !hasTokenAt(tokens, 3, 1, 3, TokenTypeKeyword) {
			t.Error("expected for keyword at 3:1 with length 3")
		}
	})

	// Position assertions for "if/else keywords" — needs docs accessor for else
	t.Run("if/else keyword positions", func(t *testing.T) {
		doc := parseTestDoc(tests["if/else keywords"].content)
		spWithDocs := &semanticTokensProvider{
			fnChecker: &stubFnChecker{names: map[string]bool{}},
			docs:      &stubDocAccessor{docs: []*Document{doc}},
		}
		result, err := spWithDocs.SemanticTokensFull(doc)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		tokens := decodeTokens(result.Data)

		if !hasTokenAt(tokens, 2, 0, 5, TokenTypeKeyword) {
			t.Error("expected templ keyword at 2:0 with length 5")
		}
		if !hasTokenAt(tokens, 3, 1, 2, TokenTypeKeyword) {
			t.Error("expected if keyword at 3:1 with length 2")
		}
		if !hasTokenAt(tokens, 5, 3, 4, TokenTypeKeyword) {
			t.Error("expected else keyword at 5:3 with length 4")
		}
	})

	// Verify "else" inside a string does not produce a false-positive keyword token.
	// The real else keyword is on line 7 ("} else {"), not inside the Sprintf on line 6.
	t.Run("else inside string not matched", func(t *testing.T) {
		content := `package main

import "fmt"

templ Cond(show bool) {
	if show {
		<span>{fmt.Sprintf("something else happened")}</span>
	} else {
		<span>fallback</span>
	}
}
`
		doc := parseTestDoc(content)
		spWithDocs := &semanticTokensProvider{
			fnChecker: &stubFnChecker{names: map[string]bool{}},
			docs:      &stubDocAccessor{docs: []*Document{doc}},
		}
		result, err := spWithDocs.SemanticTokensFull(doc)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		tokens := decodeTokens(result.Data)

		// The else keyword must be on line 7 (0-indexed) at col 3, not on line 6
		// where "else" appears inside a string literal.
		if !hasTokenAt(tokens, 7, 3, 4, TokenTypeKeyword) {
			t.Error("expected else keyword at 7:3 with length 4")
		}
		// The old findElseKeyword would have matched "else" on line 6 inside the
		// Sprintf string. Verify no keyword token points at that false position.
		// "else" in the string starts around col 30+ on line 6.
		if hasTokenAt(tokens, 6, 30, 4, TokenTypeKeyword) || hasTokenAt(tokens, 6, 31, 4, TokenTypeKeyword) || hasTokenAt(tokens, 6, 32, 4, TokenTypeKeyword) {
			t.Error("false-positive: keyword token found at the 'else' position inside string literal on line 6")
		}
	})

	// Verify bare else syntax gets a semantic token for the "else" keyword.
	t.Run("bare else keyword highlighted", func(t *testing.T) {
		content := `package main

templ Cond(show bool) {
	if show {
		<span>Yes</span>
	} else {
		<span>No</span>
	}
}
`
		doc := parseTestDoc(content)
		spWithDocs := &semanticTokensProvider{
			fnChecker: &stubFnChecker{names: map[string]bool{}},
			docs:      &stubDocAccessor{docs: []*Document{doc}},
		}
		result, err := spWithDocs.SemanticTokensFull(doc)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		tokens := decodeTokens(result.Data)

		// "else" in "} else {" on line 5 (0-indexed), col 3 (after "\t} ")
		if !hasTokenAt(tokens, 5, 3, 4, TokenTypeKeyword) {
			t.Error("expected else keyword at 5:3 with length 4 for bare else syntax")
		}
	})
}

func TestSemanticTokens_ElementAttributes(t *testing.T) {
	type tc struct {
		content  string
		wantAttr int // minimum number of attribute tokens (emitted as TokenTypeFunction)
	}

	tests := map[string]tc{
		"element with attributes": {
			content: `package main

templ Hello() {
	<div class="border-single" id="main">
		<span>Hello</span>
	</div>
}
`,
			wantAttr: 2, // class, id
		},
	}

	sp := newTestSemanticProvider()

	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			doc := parseTestDoc(tt.content)
			result, err := sp.SemanticTokensFull(doc)
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}

			tokens := decodeTokens(result.Data)

			// The provider emits attribute names as TokenTypeFunction
			funcCount := countByType(tokens, TokenTypeFunction)
			if funcCount < tt.wantAttr {
				t.Errorf("got %d function/attribute tokens, want at least %d", funcCount, tt.wantAttr)
			}
		})
	}
}

func TestSemanticTokens_Comments(t *testing.T) {
	type tc struct {
		content     string
		wantComment int
	}

	tests := map[string]tc{
		"line comment": {
			content: `package main

// A comment
templ Hello() {
	<span>Hello</span>
}
`,
			wantComment: 1,
		},
		"block comment": {
			content: `package main

/* Block comment */
templ Hello() {
	<span>Hello</span>
}
`,
			wantComment: 1,
		},
		"comment inside component": {
			content: `package main

templ Hello() {
	// inner comment
	<span>Hello</span>
}
`,
			wantComment: 1,
		},
	}

	sp := newTestSemanticProvider()

	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			doc := parseTestDoc(tt.content)
			result, err := sp.SemanticTokensFull(doc)
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}

			tokens := decodeTokens(result.Data)

			commentCount := countByType(tokens, TokenTypeComment)
			if commentCount < tt.wantComment {
				t.Errorf("got %d comment tokens, want at least %d", commentCount, tt.wantComment)
			}
		})
	}
}