gitstack

grindlemire/go-tui code browser

11.3 KB Go 470 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
package tuigen

import (
	"strings"
)

// parseFuncOrComponent parses a func definition and determines if it's a component or helper function.
// If the return type is exactly "Element", it's parsed as a component with DSL body.
// Otherwise, it's captured as raw Go code.
func (p *Parser) parseFuncOrComponent() Node {
	pos := p.position()
	startPos := p.current.StartPos

	if !p.expect(TokenFunc) {
		return nil
	}

	// Check for method receiver: func (receiver Type) Name()
	// If we see '(' after 'func', this is a method - capture as raw Go
	if p.current.Type == TokenLParen {
		return p.captureRawGoFunc(startPos, pos)
	}

	if p.current.Type != TokenIdent {
		p.errors.AddError(p.position(), "expected function name")
		return nil
	}

	name := p.current.Literal
	p.advance()

	// Generic function: func foo[T any](...) — capture as raw Go code.
	// Generic functions can't be templ components, so treat them like method receivers.
	if p.current.Type == TokenLBracket {
		return p.captureRawGoFunc(startPos, pos)
	}

	// Parse parameters
	if !p.expect(TokenLParen) {
		return nil
	}

	params := p.parseParams()

	if !p.expect(TokenRParen) {
		return nil
	}

	// Check for return type
	// Skip newlines but preserve position tracking
	p.skipNewlines()

	returnType := ""
	if p.current.Type == TokenIdent {
		returnType = p.current.Literal
		p.advance()
	}

	p.skipNewlines()

	// Decision: if return type is exactly "Element", parse as component with DSL body
	if returnType == "Element" {
		comp := &Component{
			Name:       name,
			Params:     params,
			ReturnType: "*element.Element", // Internal representation stays the same
			Position:   pos,
		}

		// Parse body as DSL
		openBraceLine := p.current.Line
		if !p.expect(TokenLBrace) {
			return nil
		}

		// Check for trailing comment on the same line as opening brace
		comp.TrailingComments = p.getTrailingCommentOnLine(openBraceLine)

		p.skipNewlines()
		comp.Body, comp.OrphanComments = p.parseComponentBodyWithOrphans()

		if !p.expectSkipNewlines(TokenRBrace) {
			return nil
		}

		return comp
	}

	// Not a component - capture as raw Go function
	// We need to continue from where we left off to capture the full function
	// Skip to matching closing brace
	braceDepth := 0
	started := false

	for p.current.Type != TokenEOF {
		switch p.current.Type {
		case TokenLBrace:
			braceDepth++
			started = true
		case TokenRBrace:
			braceDepth--
			if started && braceDepth == 0 {
				// Capture raw source from func to after closing brace
				endPos := p.current.StartPos + 1 // +1 to include the '}'
				code := p.lexer.SourceRange(startPos, endPos)
				p.clearPendingComments()
				p.advance() // move past '}'
				p.skipNewlines()
				return &GoFunc{
					Code:     code,
					Position: pos,
				}
			}
		}
		p.advance()
	}

	// If we reach here, function was not properly closed
	p.errors.AddError(pos, "unterminated function definition")
	code := p.lexer.SourceRange(startPos, p.lexer.SourcePos())
	p.skipNewlines()

	return &GoFunc{
		Code:     code,
		Position: pos,
	}
}

// parseGoDecl parses a top-level Go declaration (type, const, or var).
// These are captured as raw Go code and passed through unchanged.
func (p *Parser) parseGoDecl() *GoDecl {
	pos := p.position()
	startPos := p.current.StartPos
	kind := p.current.Literal // "type", "const", or "var"

	// Advance past the keyword
	p.advance()

	// Check if this is a grouped declaration: var (...) or const (...)
	// A grouped declaration has ( immediately after the keyword (possibly with whitespace)
	isGrouped := p.current.Type == TokenLParen

	// Track brace/paren depth to find end of declaration
	braceDepth := 0
	parenDepth := 0

	for p.current.Type != TokenEOF {
		switch p.current.Type {
		case TokenLBrace:
			braceDepth++
		case TokenRBrace:
			braceDepth--
			if braceDepth == 0 && parenDepth == 0 {
				// End of braced declaration (type struct{}, const/var block)
				endPos := p.current.StartPos + 1
				code := p.lexer.SourceRange(startPos, endPos)
				p.clearPendingComments()
				p.advance()
				p.skipNewlines()
				return &GoDecl{Kind: kind, Code: code, Position: pos}
			}
		case TokenLParen:
			parenDepth++
		case TokenRParen:
			parenDepth--
			if isGrouped && braceDepth == 0 && parenDepth == 0 {
				// End of grouped declaration: const (...) or var (...)
				endPos := p.current.StartPos + 1
				code := p.lexer.SourceRange(startPos, endPos)
				p.clearPendingComments()
				p.advance()
				p.skipNewlines()
				return &GoDecl{Kind: kind, Code: code, Position: pos}
			}
		case TokenNewline:
			// Simple declaration ends at newline (if not inside braces/parens)
			if braceDepth == 0 && parenDepth == 0 {
				endPos := p.current.StartPos
				code := p.lexer.SourceRange(startPos, endPos)
				p.skipNewlines()
				return &GoDecl{Kind: kind, Code: code, Position: pos}
			}
		}
		p.advance()
	}

	// Handle EOF
	code := p.lexer.SourceRange(startPos, p.lexer.SourcePos())
	return &GoDecl{Kind: kind, Code: code, Position: pos}
}

// captureRawGoFunc captures a function definition as raw Go code.
// Used for methods with receivers and helper functions.
func (p *Parser) captureRawGoFunc(startPos int, pos Position) *GoFunc {
	braceDepth := 0
	started := false

	for p.current.Type != TokenEOF {
		switch p.current.Type {
		case TokenLBrace:
			braceDepth++
			started = true
		case TokenRBrace:
			braceDepth--
			if started && braceDepth == 0 {
				endPos := p.current.StartPos + 1
				code := p.lexer.SourceRange(startPos, endPos)
				p.clearPendingComments()
				p.advance()
				p.skipNewlines()
				return &GoFunc{Code: code, Position: pos}
			}
		}
		p.advance()
	}

	p.errors.AddError(pos, "unterminated function definition")
	code := p.lexer.SourceRange(startPos, p.lexer.SourcePos())
	return &GoFunc{Code: code, Position: pos}
}

// parseTempl parses a templ definition which is always a component.
// Supports two forms:
//
//	templ Name(params) { body }           — function component (existing)
//	templ (s *sidebar) Render() { body }  — method component (new)
//
// After 'templ', '(' means a method receiver; an identifier means a function name.
func (p *Parser) parseTempl() *Component {
	pos := p.position()

	if !p.expect(TokenTempl) {
		return nil
	}

	// Disambiguation: '(' after templ means method receiver, identifier means function name
	if p.current.Type == TokenLParen {
		return p.parseMethodTempl(pos)
	}

	if p.current.Type != TokenIdent {
		p.errors.AddError(p.position(), "expected component name or method receiver")
		return nil
	}

	name := p.current.Literal
	p.advance()

	// Parse parameters
	if !p.expect(TokenLParen) {
		return nil
	}

	params := p.parseParams()

	if !p.expect(TokenRParen) {
		return nil
	}

	p.skipNewlines()

	comp := &Component{
		Name:       name,
		Params:     params,
		ReturnType: "*element.Element",
		Position:   pos,
	}

	// Parse body as DSL (function templ — inMethodTempl stays false)
	openBraceLine := p.current.Line
	if !p.expect(TokenLBrace) {
		return nil
	}

	// Check for trailing comment on the same line as opening brace
	comp.TrailingComments = p.getTrailingCommentOnLine(openBraceLine)

	p.skipNewlines()
	comp.Body, comp.OrphanComments = p.parseComponentBodyWithOrphans()

	if !p.expectSkipNewlines(TokenRBrace) {
		return nil
	}

	return comp
}

// parseMethodTempl parses a method-style templ: templ (s *sidebar) Render() { body }
// Called after 'templ' has been consumed and current token is '('.
func (p *Parser) parseMethodTempl(pos Position) *Component {
	// Consume '('
	p.advance()

	// Parse receiver: name *Type or name Type
	if p.current.Type != TokenIdent {
		p.errors.AddError(p.position(), "expected receiver name")
		return nil
	}
	receiverName := p.current.Literal
	p.advance()

	// Parse receiver type — capture raw source until closing ')'
	typeStart := p.current.StartPos
	depth := 0
	for p.current.Type != TokenEOF {
		if p.current.Type == TokenLParen {
			depth++
		} else if p.current.Type == TokenRParen {
			if depth == 0 {
				break
			}
			depth--
		}
		p.advance()
	}
	receiverType := strings.TrimSpace(p.lexer.SourceRange(typeStart, p.current.StartPos))

	if !p.expect(TokenRParen) {
		return nil
	}

	// Full receiver text: "name Type"
	receiver := receiverName + " " + receiverType

	// Parse method name — must be 'Render'
	if p.current.Type != TokenIdent {
		p.errors.AddError(p.position(), "expected method name after receiver")
		return nil
	}
	name := p.current.Literal
	if name != "Render" {
		p.errors.AddErrorf(p.position(), "method templ name must be 'Render', got %q", name)
		return nil
	}
	p.advance()

	// Parse empty parameter list — method templs don't accept params
	if !p.expect(TokenLParen) {
		return nil
	}

	if p.current.Type != TokenRParen {
		p.errors.AddError(p.position(), "method templ Render() must not have parameters")
		return nil
	}

	if !p.expect(TokenRParen) {
		return nil
	}

	p.skipNewlines()

	comp := &Component{
		Name:         name,
		ReturnType:   "*element.Element",
		Position:     pos,
		Receiver:     receiver,
		ReceiverName: receiverName,
		ReceiverType: receiverType,
	}

	// Set method templ context so parseComponentCall sets IsStructMount
	p.inMethodTempl = true
	defer func() { p.inMethodTempl = false }()

	// Parse body as DSL
	openBraceLine := p.current.Line
	if !p.expect(TokenLBrace) {
		return nil
	}

	// Check for trailing comment on the same line as opening brace
	comp.TrailingComments = p.getTrailingCommentOnLine(openBraceLine)

	p.skipNewlines()
	comp.Body, comp.OrphanComments = p.parseComponentBodyWithOrphans()

	if !p.expectSkipNewlines(TokenRBrace) {
		return nil
	}

	return comp
}

// parseParams parses function parameters.
func (p *Parser) parseParams() []*Param {
	var params []*Param
	p.skipNewlines()

	for p.current.Type != TokenRParen && p.current.Type != TokenEOF {
		param := p.parseParam()
		if param != nil {
			params = append(params, param)
		}
		p.skipNewlines()

		if p.current.Type == TokenComma {
			p.advance()
			p.skipNewlines()
			// Allow trailing comma before ')'.
			if p.current.Type == TokenRParen {
				break
			}
		} else {
			break
		}
	}

	return params
}

// parseParam parses a single parameter: name Type
func (p *Parser) parseParam() *Param {
	pos := p.position()

	if p.current.Type != TokenIdent {
		p.errors.AddError(p.position(), "expected parameter name")
		return nil
	}

	name := p.current.Literal
	p.advance()

	// Parse type (could be complex like *element.Element, []string, func())
	typeStr := p.parseType()
	if typeStr == "" {
		return nil
	}

	return &Param{
		Name:     name,
		Type:     typeStr,
		Position: pos,
	}
}

// parseType parses a Go type expression by capturing raw source.
// This handles all Go types including generics, channels, and complex function signatures.
func (p *Parser) parseType() string {
	startPos := p.current.StartPos
	depth := 0 // track [], (), {}

	for p.current.Type != TokenEOF {
		switch p.current.Type {
		case TokenComma:
			// Comma at depth 0 means end of this type
			if depth == 0 {
				return strings.TrimSpace(p.lexer.SourceRange(startPos, p.current.StartPos))
			}
			p.advance()
		case TokenRParen:
			// Right paren at depth 0 means end of parameter list
			if depth == 0 {
				return strings.TrimSpace(p.lexer.SourceRange(startPos, p.current.StartPos))
			}
			depth--
			p.advance()
		case TokenLBracket, TokenLParen, TokenLBrace:
			depth++
			p.advance()
		case TokenRBracket, TokenRBrace:
			depth--
			p.advance()
		default:
			p.advance()
		}
	}

	return strings.TrimSpace(p.lexer.SourceRange(startPos, p.lexer.SourcePos()))
}