gitstack

grindlemire/go-tui code browser

13.7 KB Go 498 lines 2026-06-12 · f0bb13a 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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
package tuigen

import (
	"strconv"
	"strings"
)

// parseComponentBody parses the body of a component.
func (p *Parser) parseComponentBody() []Node {
	nodes, _ := p.parseComponentBodyWithOrphans()
	return nodes
}

// parseComponentBodyWithOrphans parses the body of a component and also
// returns any orphan comments that weren't attached to nodes.
func (p *Parser) parseComponentBodyWithOrphans() ([]Node, []*CommentGroup) {
	var nodes []Node
	var orphanComments []*CommentGroup

	for p.current.Type != TokenRBrace && p.current.Type != TokenEOF {
		p.skipNewlines()
		if p.current.Type == TokenRBrace || p.current.Type == TokenEOF {
			break
		}

		// Collect any pending comments before parsing the next node
		leadingComments := p.getLeadingCommentGroup()

		node := p.parseBodyNode()
		if node != nil {
			// Attach leading comments to the node
			p.attachLeadingComments(node, leadingComments)
			nodes = append(nodes, node)
		} else if leadingComments != nil {
			// No node was parsed, these comments are orphans
			orphanComments = append(orphanComments, leadingComments)
		}
	}

	// Collect any remaining orphan comments before the closing brace
	p.collectPendingComments()
	remaining := p.consumePendingComments()
	if len(remaining) > 0 {
		orphanComments = append(orphanComments, groupComments(remaining)...)
	}

	return nodes, orphanComments
}

// attachLeadingComments attaches leading comments to a node.
// This handles all node types that support LeadingComments.
func (p *Parser) attachLeadingComments(node Node, comments *CommentGroup) {
	if comments == nil {
		return
	}

	switch n := node.(type) {
	case *Element:
		n.LeadingComments = comments
	case *LetBinding:
		n.LeadingComments = comments
	case *ForLoop:
		n.LeadingComments = comments
	case *IfStmt:
		n.LeadingComments = comments
	case *ComponentCall:
		n.LeadingComments = comments
	case *ComponentExpr:
		n.LeadingComments = comments
	case *GoCode:
		n.LeadingComments = comments
	case *GoExpr:
		n.LeadingComments = comments
	case *ChildrenSlot:
		n.LeadingComments = comments
	}
}

// parseBodyNode parses a single node in a component/element body.
// NOTE: We explicitly check for nil before returning to avoid the Go interface
// nil gotcha where a typed nil pointer (e.g., (*ComponentCall)(nil)) converted
// to an interface would pass `node != nil` checks in callers.
func (p *Parser) parseBodyNode() Node {
	// Try control flow and binding dispatch first
	if node := p.parseControlFlowOrBinding(); node != nil {
		return node
	}

	switch p.current.Type {
	case TokenLAngle:
		if el := p.parseElement(); el != nil {
			return el
		}
	case TokenLBrace:
		if node := p.parseGoExprOrChildrenSlot(); node != nil {
			return node
		}
	case TokenIdent, TokenVar, TokenFor, TokenFunc, TokenReturn:
		// Raw Go statement (e.g., fmt.Printf("x"), x := 1, for i := 0; ...)
		// Note: go, defer, switch, select are lexed as TokenIdent
		// TokenFor lands here for C-style for loops (isRangeForLoop returned false)
		// TokenVar lands here for plain Go var declarations (not var name = <element>)
		if stmt := p.parseGoStatement(); stmt != nil {
			return stmt
		}
	case TokenError:
		// Lexer already reported the diagnostic (e.g. "@let is no longer supported").
		// Just advance past the error token without emitting a second error.
		p.advance()
	default:
		p.errors.AddErrorf(p.position(), "unexpected token %s in body", p.current.Type)
		p.advance()
	}
	return nil
}

// parseControlFlowOrBinding attempts to parse a control flow node (if/for)
// or a binding (name := <element>, var name = <element>) from the current token.
// Returns the parsed node, or nil if the current token doesn't match.
// When nil is returned, the token cursor is guaranteed to be unchanged (via save/restore).
func (p *Parser) parseControlFlowOrBinding() Node {
	switch p.current.Type {
	case TokenFor:
		if !p.isRangeForLoop() {
			return nil // C-style for, let caller handle as GoCode
		}
		saved := p.saveState()
		if f := p.parseFor(); f != nil {
			return f
		}
		p.restoreState(saved)
	case TokenIf:
		saved := p.saveState()
		if i := p.parseIf(); i != nil {
			return i
		}
		p.restoreState(saved)
	case TokenAtCall:
		saved := p.saveState()
		if call := p.parseComponentCall(); call != nil {
			return call
		}
		p.restoreState(saved)
	case TokenAtExpr:
		if expr := p.parseComponentExpr(); expr != nil {
			return expr
		}
	case TokenVar:
		if p.peek.Type == TokenIdent {
			saved := p.saveState()
			if let := p.parseVarBinding(); let != nil {
				return let
			}
			p.restoreState(saved)
		}
		return nil
	case TokenIdent:
		if p.peek.Type == TokenColonEquals {
			saved := p.saveState()
			name := p.current.Literal
			pos := p.position()
			p.advance() // consume ident
			p.advance() // consume :=
			p.skipNewlines()

			if (p.current.Type == TokenLAngle && p.peek.Type != TokenMinus) || p.current.Type == TokenAtCall || p.current.Type == TokenAtExpr {
				if let := p.parseShortBinding(name, pos); let != nil {
					return let
				}
			}
			p.restoreState(saved)
		}
		return nil
	}
	return nil
}

// parseElement parses an XML-like element.
func (p *Parser) parseElement() *Element {
	pos := p.position()

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

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

	elem := &Element{
		Tag:      p.current.Literal,
		Position: pos,
	}
	p.advance()

	// Parse attributes (ref={} and key={} are parsed as regular attributes, then extracted)
	elem.Attributes = p.parseAttributes()

	// Detect multi-line attributes from source positions
	if len(elem.Attributes) > 0 {
		lastAttr := elem.Attributes[len(elem.Attributes)-1]
		elem.MultiLineAttrs = lastAttr.Position.Line != pos.Line
	}

	// Extract ref={expr} attribute and move it to RefExpr
	for i, attr := range elem.Attributes {
		if attr.Name == "ref" {
			if expr, ok := attr.Value.(*GoExpr); ok {
				elem.RefExpr = expr
				// Remove ref from attributes
				elem.Attributes = append(elem.Attributes[:i], elem.Attributes[i+1:]...)
				break
			}
		}
	}

	// Check for key={expr} attribute and move it to RefKey
	for i, attr := range elem.Attributes {
		if attr.Name == "key" {
			if expr, ok := attr.Value.(*GoExpr); ok {
				elem.RefKey = expr
				// Remove key from attributes
				elem.Attributes = append(elem.Attributes[:i], elem.Attributes[i+1:]...)
				break
			}
		}
	}

	// Determine the line of the last thing before the closing bracket
	lastLineBeforeBracket := pos.Line
	if len(elem.Attributes) > 0 {
		lastLineBeforeBracket = elem.Attributes[len(elem.Attributes)-1].Position.Line
	}

	// Check for self-closing or opening tag
	if p.current.Type == TokenSlashAngle {
		// Self-closing: <tag />
		elem.SelfClose = true
		elem.ClosingBracketNewLine = p.current.Line > lastLineBeforeBracket
		closeLine := p.current.Line
		p.advanceSkipNewlines()
		// Check for trailing comment on same line as />
		elem.TrailingComments = p.getTrailingCommentOnLine(closeLine)
		return elem
	}

	// Detect closing bracket on new line for regular elements
	elem.ClosingBracketNewLine = p.current.Line > lastLineBeforeBracket
	openTagEndLine := p.current.Line // line of >

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

	// Parse children
	elem.Children, elem.OrphanComments = p.parseChildren(elem.Tag)

	// Detect inline children from source positions
	if len(elem.Children) > 0 {
		firstChild := elem.Children[0]
		elem.InlineChildren = firstChild.Pos().Line == openTagEndLine
	} else {
		// Empty elements are always inline: <div></div>
		elem.InlineChildren = true
	}

	// Expect closing tag </tag>
	if p.current.Type != TokenLAngleSlash {
		p.errors.AddErrorf(p.position(), "expected closing tag </%s>", elem.Tag)
		return elem
	}
	p.advance()

	if p.current.Type != TokenIdent || p.current.Literal != elem.Tag {
		p.errors.AddErrorf(p.position(), "mismatched closing tag: expected </%s>, got </%s>", elem.Tag, p.current.Literal)
	}
	if p.current.Type == TokenIdent {
		p.advance()
	}

	closeLine := p.current.Line
	if !p.expect(TokenRAngle) {
		return elem
	}

	// Check for trailing comment on same line as closing >
	elem.TrailingComments = p.getTrailingCommentOnLine(closeLine)

	return elem
}

// parseAttributes parses element attributes.
func (p *Parser) parseAttributes() []*Attribute {
	var attrs []*Attribute

	for {
		// Skip newlines between attributes (for multi-line attribute lists)
		p.skipNewlines()

		// Stop if we hit end of attributes (> or /> or EOF)
		if p.current.Type != TokenIdent {
			break
		}

		attr := p.parseAttribute()
		if attr != nil {
			attrs = append(attrs, attr)
		}
	}

	return attrs
}

// parseAttribute parses a single attribute: name=value or name={expr} or just name (boolean)
func (p *Parser) parseAttribute() *Attribute {
	pos := p.position()

	if p.current.Type != TokenIdent {
		return nil
	}

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

	// Check for shorthand boolean attribute (no =)
	if p.current.Type != TokenEquals {
		return &Attribute{
			Name:          name,
			Value:         &BoolLit{Value: true, Position: pos},
			Position:      pos,
			ValuePosition: pos,
		}
	}

	p.advance() // consume =

	// Record the position of the value (after the '=')
	valuePos := p.position()

	// Parse value
	var value Node
	switch p.current.Type {
	case TokenString:
		value = &StringLit{Value: p.current.Literal, Position: p.position()}
		// For string literals, the value position should be inside the quotes
		// The current position is at the opening quote, so add 1 for the quote
		valuePos = p.position()
		valuePos.Column++ // Move past the opening quote
		p.advance()
	case TokenInt:
		v, _ := strconv.ParseInt(p.current.Literal, 10, 64)
		value = &IntLit{Value: v, Position: p.position()}
		p.advance()
	case TokenFloat:
		v, _ := strconv.ParseFloat(p.current.Literal, 64)
		value = &FloatLit{Value: v, Position: p.position()}
		p.advance()
	case TokenLBrace:
		value = p.parseGoExprNode()
	case TokenIdent:
		// Could be true, false, or other identifier
		switch p.current.Literal {
		case "true":
			value = &BoolLit{Value: true, Position: p.position()}
			p.advance()
		case "false":
			value = &BoolLit{Value: false, Position: p.position()}
			p.advance()
		default:
			// Treat as identifier expression
			value = &GoExpr{Code: p.current.Literal, Position: p.position()}
			p.advance()
		}
	default:
		p.errors.AddErrorf(p.position(), "expected attribute value, got %s", p.current.Type)
		return nil
	}

	return &Attribute{
		Name:          name,
		Value:         value,
		Position:      pos,
		ValuePosition: valuePos,
	}
}

// parseChildren parses children inside an element until the closing tag.
// Returns the child nodes and any orphan comments not attached to a node.
func (p *Parser) parseChildren(parentTag string) ([]Node, []*CommentGroup) {
	var children []Node
	var orphanComments []*CommentGroup

	for {
		// Count newlines to detect blank lines between siblings
		nlCount := 0
		for p.current.Type == TokenNewline {
			nlCount++
			p.advance()
		}
		hadBlankLine := nlCount >= 2

		// Check for closing tag — consume any pending comments as orphans first
		if p.current.Type == TokenLAngleSlash || p.current.Type == TokenEOF {
			p.collectPendingComments()
			remaining := p.consumePendingComments()
			if len(remaining) > 0 {
				orphanComments = append(orphanComments, groupComments(remaining)...)
			}
			break
		}

		// Collect any pending comments before parsing the next child
		leadingComments := p.getLeadingCommentGroup()

		// Parse child based on token type
		var child Node

		// Try control flow and binding dispatch first
		if node := p.parseControlFlowOrBinding(); node != nil {
			child = node
		} else if p.current.Type == TokenLAngle {
			// Nested element
			if elem := p.parseElement(); elem != nil {
				child = elem
			}
		} else if p.current.Type == TokenLBrace {
			// Go expression or children slot
			child = p.parseGoExprOrChildrenSlot()
		} else {
			// Coalesce consecutive text tokens into a single TextContent.
			// In element content, we treat identifiers and various punctuation as text
			// until we hit a special delimiter ({, <, @, newline, EOF, or closing tag).
			if isTextToken(p.current.Type) {
				var text strings.Builder
				textPos := p.position()
				prevTokenEnd := -1
				for isTextToken(p.current.Type) {
					// Use source positions to detect whitespace: if there's a gap
					// between the end of the previous token and the start of the
					// current one, the original source had whitespace there.
					if text.Len() > 0 && prevTokenEnd >= 0 && p.current.StartPos > prevTokenEnd {
						text.WriteByte(' ')
					}
					text.WriteString(p.current.Literal)
					prevTokenEnd = p.current.StartPos + len(p.current.Literal)
					p.advance()
				}
				child = &TextContent{
					Text:     text.String(),
					Position: textPos,
				}
			} else if p.current.Type != TokenEOF && p.current.Type != TokenLAngleSlash {
				// Skip unknown tokens in children context
				p.advance()
			} else {
				break
			}
		}

		// Attach leading comments to the child if one was parsed
		if child != nil {
			// Mark blank line before non-first children
			if hadBlankLine && len(children) > 0 {
				setBlankLineBefore(child, true)
			}
			p.attachLeadingComments(child, leadingComments)
			children = append(children, child)
		} else if leadingComments != nil {
			// No node was parsed, these comments are orphans
			orphanComments = append(orphanComments, leadingComments)
		}
	}

	return children, orphanComments
}

// setBlankLineBefore sets the BlankLineBefore field on a node.
func setBlankLineBefore(node Node, v bool) {
	switch n := node.(type) {
	case *Element:
		n.BlankLineBefore = v
	case *GoExpr:
		n.BlankLineBefore = v
	case *TextContent:
		n.BlankLineBefore = v
	case *LetBinding:
		n.BlankLineBefore = v
	case *ForLoop:
		n.BlankLineBefore = v
	case *IfStmt:
		n.BlankLineBefore = v
	case *ComponentCall:
		n.BlankLineBefore = v
	case *ChildrenSlot:
		n.BlankLineBefore = v
	}
}