gitstack

grindlemire/go-tui code browser

16.6 KB Go 571 lines 2026-07-10 ยท 0592ab2 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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
package tuigen

import (
	"bytes"
	"fmt"
	"go/format"
	"slices"
	"strings"

	"golang.org/x/tools/imports"
)

// Generator transforms a validated AST into Go source code.
type Generator struct {
	buf        bytes.Buffer
	indent     int
	varCounter int
	sourceFile string // original .gsx filename for header comment

	// Refs tracking for current component
	refs []RefInfo

	// Component calls with watchers that need aggregation
	componentVars []componentVarEntry

	// State tracking for current component (for reactive bindings)
	stateVars     []StateVar
	stateBindings []StateBinding

	// Events tracking for current component (for BindApp generation)
	eventsVars []EventsVar

	// componentExprFields tracks receiver field names used as component expressions
	// (e.g., "settingsView" from @c.settingsView) in method components.
	// These fields need BindApp calls in the generated BindApp method.
	componentExprFields []string

	// Conditional counter for reactive if wrapper elements (__cond_0, __cond_1, etc.)
	condCounter int

	// Loop counter for reactive for wrapper elements (__loop_0, __loop_1, etc.)
	loopCounter int

	// Mount index counter for struct component @Component() calls in method templs.
	// Reset per method component. Assigns position indices to app.Mount() calls.
	mountIndex int

	// currentReceiver is the receiver variable name for the current method templ.
	// Set during generateMethodComponent, used by generateComponentCallWithRefs
	// to emit app.Mount(receiverVar, index, factory).
	currentReceiver string

	// loopIndexStack names synthetic loop index variables (__idx_N) by depth.
	loopIndexStack []string

	// mountKeyParts holds the identity segments in scope for mount key expressions.
	mountKeyParts []mountKeySegment

	// fileDecls stores the current file's GoDecl nodes for struct lookup.
	// Used by generateUpdateProps to find struct definitions for method components.
	fileDecls []*GoDecl

	// fileFuncs stores the current file's top-level Go functions/methods.
	// Used to detect user-defined BindApp methods and avoid duplicate generation.
	fileFuncs []*GoFunc

	// pkgCtx holds declarations from sibling files of the package, so
	// user-defined lifecycle methods declared outside this .gsx file also
	// suppress generation. Nil when no context is available.
	pkgCtx *PackageContext

	// SkipImports uses format.Source instead of imports.Process (faster for tests)
	SkipImports bool

	// Source map tracking
	sourceMap   *SourceMap
	currentLine int // current line in generated output (0-indexed)

	// functionTempls tracks function templ names (no receiver) in the current file.
	// Used to avoid mounting function templs via app.Mount() from method templs โ€”
	// they should be called directly since they're stateless view functions.
	functionTempls map[string]bool

	tuiAlias     string
	isTuiPackage bool
}

// componentVarEntry tracks a function component call variable for watcher/bind aggregation.
type componentVarEntry struct {
	name          string // generated variable name (e.g., "__tui_2")
	componentName string // component function name (e.g., "Badge" or "pkg.Badge")
	inConditional bool   // true when declared inside an if/else or for-loop block scope
	inForLoop     bool   // true when declared inside a for-loop body (needs slice collection)
}

// viewTypeName returns the view struct pointer type for a component name.
// e.g., "Badge" -> "*BadgeView", "pkg.Badge" -> "*pkg.BadgeView"
func viewTypeName(componentName string) string {
	if idx := strings.LastIndex(componentName, "."); idx != -1 {
		pkg := componentName[:idx]
		name := componentName[idx+1:]
		return "*" + pkg + "." + name + "View"
	}
	return "*" + componentName + "View"
}

// NewGenerator creates a new code generator.
func NewGenerator() *Generator {
	return &Generator{}
}

// SetPackageContext supplies declarations from sibling files of the package.
// User-defined lifecycle methods found there suppress generation the same as
// declarations in the .gsx file itself.
func (g *Generator) SetPackageContext(ctx *PackageContext) {
	g.pkgCtx = ctx
}

// Generate produces Go source code from a parsed and analyzed AST.
// Returns the generated code as a byte slice, or an error if generation fails.
func (g *Generator) Generate(file *File, sourceFile string) ([]byte, error) {
	g.buf.Reset()
	g.varCounter = 0
	g.sourceFile = sourceFile
	g.sourceMap = NewSourceMap(sourceFile)
	g.currentLine = 0

	// Detect go-tui package alias and package name
	g.tuiAlias = "tui"
	for _, imp := range file.Imports {
		if imp.Path == "github.com/grindlemire/go-tui" {
			if imp.Alias != "" {
				g.tuiAlias = imp.Alias
			}
			break
		}
	}
	g.isTuiPackage = (file.Package == "tui")

	// Generate header
	g.generateHeader()

	// Generate package
	g.generatePackage(file.Package)

	// Generate imports
	g.generateImports(file.Imports)

	// Track where content after imports starts (for source map adjustment)
	firstContentLine := g.currentLine

	// Store file decls for struct lookup in generateUpdateProps
	g.fileDecls = file.Decls
	g.fileFuncs = file.Funcs

	// Build function templ lookup so method templs can call them directly
	// instead of mounting them via app.Mount() (which would cache stale views).
	g.functionTempls = make(map[string]bool)
	for _, comp := range file.Components {
		if comp.Receiver == "" {
			g.functionTempls[comp.Name] = true
		}
	}

	// Generate top-level Go declarations (type, const, var)
	for _, decl := range file.Decls {
		g.generateGoDecl(decl)
	}

	// Generate top-level Go functions
	for _, fn := range file.Funcs {
		g.generateGoFunc(fn)
	}

	// Generate components
	for _, comp := range file.Components {
		g.generateComponent(comp)
	}

	// Emit compile-time interface checks for method components that define
	// optional interface methods (KeyMap, HandleMouse, Init, Watchers).
	g.generateInterfaceChecks(file)

	// For tests: just format without import processing (much faster)
	if g.SkipImports {
		return format.Source(g.buf.Bytes())
	}

	// For production: format and fix imports with goimports
	preOutput := g.buf.Bytes()
	postOutput, err := imports.Process(g.sourceFile, preOutput, nil)
	if err != nil {
		return nil, err
	}

	// Adjust source map for line shifts caused by goimports.
	// Goimports only modifies the import section, so we calculate the shift
	// by comparing line counts before and after.
	g.adjustSourceMapForGoimports(preOutput, postOutput, firstContentLine)

	return postOutput, nil
}

// adjustSourceMapForGoimports adjusts source map line numbers after goimports
// modifies the import section. We find where imports end in both versions
// and calculate the shift from that, since content after imports shifts
// by the difference in import section sizes.
func (g *Generator) adjustSourceMapForGoimports(pre, post []byte, firstContentLine int) {
	// Find where content starts in the post-goimports output.
	// This is the first non-blank line after the import block.
	postContentStart := findFirstContentLineAfterImports(post)

	// The shift is how much the content start moved
	lineShift := postContentStart - firstContentLine

	if lineShift == 0 {
		return
	}

	// Adjust all source map entries for lines at or after where content starts
	for i := range g.sourceMap.Mappings {
		if g.sourceMap.Mappings[i].GoLine >= firstContentLine {
			g.sourceMap.Mappings[i].GoLine += lineShift
		}
	}
}

// findFirstContentLineAfterImports finds the first non-blank line after the import block.
func findFirstContentLineAfterImports(code []byte) int {
	lines := bytes.Split(code, []byte("\n"))
	inImportBlock := false
	importBlockEnded := false

	for i, line := range lines {
		trimmed := bytes.TrimSpace(line)

		// Track import block
		if bytes.HasPrefix(trimmed, []byte("import (")) {
			inImportBlock = true
			continue
		}
		if inImportBlock && len(trimmed) == 1 && trimmed[0] == ')' {
			inImportBlock = false
			importBlockEnded = true
			continue
		}
		// Handle single-line imports: import "path"
		if bytes.HasPrefix(trimmed, []byte("import ")) && !bytes.HasPrefix(trimmed, []byte("import (")) {
			importBlockEnded = true
			continue
		}

		// After imports end, find first non-blank line
		if importBlockEnded && len(trimmed) > 0 {
			return i
		}
	}

	return len(lines) // Fallback if no content found
}

// GetSourceMap returns the source map generated during code generation.
// Must be called after Generate().
func (g *Generator) GetSourceMap() *SourceMap {
	return g.sourceMap
}

// generateHeader writes the "DO NOT EDIT" comment.
func (g *Generator) generateHeader() {
	g.writeln("// Code generated by tui generate. DO NOT EDIT.")
	if g.sourceFile != "" {
		g.writef("// Source: %s\n", g.sourceFile)
	}
	g.writeln("")
}

// generatePackage writes the package declaration.
func (g *Generator) generatePackage(pkg string) {
	g.writef("package %s\n\n", pkg)
}

// generateImports writes the import block.
func (g *Generator) generateImports(imports []Import) {
	if len(imports) == 0 {
		// Always include root tui import for generated code
		g.writeln("import (")
		g.indent++
		g.writeln(`tui "github.com/grindlemire/go-tui"`)
		g.indent--
		g.writeln(")")
		g.writeln("")
		return
	}

	// Check if root tui package is already imported
	hasTui := false
	for _, imp := range imports {
		if imp.Path == "github.com/grindlemire/go-tui" {
			hasTui = true
		}
	}

	g.writeln("import (")
	g.indent++

	for _, imp := range imports {
		if imp.Alias != "" {
			g.writef("%s %q\n", imp.Alias, imp.Path)
		} else {
			g.writef("%q\n", imp.Path)
		}
	}

	// Add required import if not present
	if !hasTui {
		g.writeln("")
		g.writeln(`tui "github.com/grindlemire/go-tui"`)
	}

	g.indent--
	g.writeln(")")
	g.writeln("")
}

// nextVar returns the next unique variable name.
func (g *Generator) nextVar() string {
	name := fmt.Sprintf("__tui_%d", g.varCounter)
	g.varCounter++
	return name
}

// nextCondVar returns the next unique conditional wrapper variable name.
func (g *Generator) nextCondVar() string {
	name := fmt.Sprintf("__cond_%d", g.condCounter)
	g.condCounter++
	return name
}

// nextLoopVar returns the next unique loop wrapper variable name.
func (g *Generator) nextLoopVar() string {
	name := fmt.Sprintf("__loop_%d", g.loopCounter)
	g.loopCounter++
	return name
}

// pushLoopIndex adds a loop index variable to the stack and returns the variable name to use.
// If the loop has a usable index variable (not "" or "_"), uses it directly.
// Otherwise, generates a synthetic index variable name.
func (g *Generator) pushLoopIndex(loop *ForLoop) string {
	var idxVar string
	if loop.Index != "" && loop.Index != "_" {
		idxVar = loop.Index
	} else {
		idxVar = fmt.Sprintf("__idx_%d", len(g.loopIndexStack))
	}
	g.loopIndexStack = append(g.loopIndexStack, idxVar)
	g.mountKeyParts = append(slices.Clone(g.mountKeyParts), mountKeySegment{expr: idxVar, fromLoop: true})
	return idxVar
}

// popLoopIndex removes the most recent loop index variable from the stack.
func (g *Generator) popLoopIndex() {
	if len(g.loopIndexStack) > 0 {
		g.loopIndexStack = g.loopIndexStack[:len(g.loopIndexStack)-1]
	}
	if len(g.mountKeyParts) > 0 {
		g.mountKeyParts = g.mountKeyParts[:len(g.mountKeyParts)-1]
	}
}

// mountKeySegment is one mount key identity segment: a loop variable or a
// key={...} expression.
type mountKeySegment struct {
	expr     string
	fromLoop bool
}

// pushElementKey scopes a key={...} override until the returned restore func
// runs: the key replaces the innermost segment when it came from a loop
// (React sibling scoping) and appends under another key (depths compose).
func (g *Generator) pushElementKey(key string) func() {
	saved := g.mountKeyParts
	parts := slices.Clone(saved)
	if n := len(parts); n > 0 && parts[n-1].fromLoop {
		parts[n-1] = mountKeySegment{expr: key}
	} else {
		parts = append(parts, mountKeySegment{expr: key})
	}
	g.mountKeyParts = parts
	return func() { g.mountKeyParts = saved }
}

// mountKeyExpr returns the mount cache key expression: the site index alone,
// or tui.MountKey(site, parts...) from the in-scope identity segments.
func (g *Generator) mountKeyExpr(baseIndex int) string {
	if len(g.mountKeyParts) == 0 {
		return fmt.Sprintf("%d", baseIndex)
	}
	exprs := make([]string, len(g.mountKeyParts))
	for i, part := range g.mountKeyParts {
		exprs[i] = part.expr
	}
	return fmt.Sprintf("tui.MountKey(%d, %s)", baseIndex, strings.Join(exprs, ", "))
}

// stateNameSet returns a set of state variable names for quick lookup.
func (g *Generator) stateNameSet() map[string]bool {
	m := make(map[string]bool)
	for _, sv := range g.stateVars {
		m[sv.Name] = true
	}
	return m
}

// write writes a string without indentation and tracks line numbers.
func (g *Generator) write(s string) {
	g.buf.WriteString(s)
	// Count newlines in the output
	for _, c := range s {
		if c == '\n' {
			g.currentLine++
		}
	}
}

// writef writes a formatted string with indentation and tracks line numbers.
func (g *Generator) writef(format string, args ...any) {
	g.writeIndent()
	s := fmt.Sprintf(format, args...)
	g.buf.WriteString(s)
	// Count newlines in the output
	for _, c := range s {
		if c == '\n' {
			g.currentLine++
		}
	}
}

// writeln writes a line with indentation and tracks line numbers.
func (g *Generator) writeln(s string) {
	if s == "" {
		g.buf.WriteByte('\n')
		g.currentLine++
		return
	}
	g.writeIndent()
	g.buf.WriteString(s)
	g.buf.WriteByte('\n')
	g.currentLine++
}

// writeIndent writes the current indentation.
func (g *Generator) writeIndent() {
	for i := 0; i < g.indent; i++ {
		g.buf.WriteByte('\t')
	}
}

// GenerateString is a convenience method that returns the generated code as a string.
func (g *Generator) GenerateString(file *File, sourceFile string) (string, error) {
	data, err := g.Generate(file, sourceFile)
	if err != nil {
		return "", err
	}
	return string(data), nil
}

// ParseAndGenerate parses source code and generates Go code in one step.
// This is a convenience function for simple use cases.
func ParseAndGenerate(filename, source string) ([]byte, error) {
	return parseAndGenerate(filename, source, false)
}

// parseAndGenerateSkipImports is like ParseAndGenerate but uses format.Source
// instead of imports.Process. This is much faster for tests.
func parseAndGenerateSkipImports(filename, source string) ([]byte, error) {
	return parseAndGenerate(filename, source, true)
}

func parseAndGenerate(filename, source string, skipImports bool) ([]byte, error) {
	lexer := NewLexer(filename, source)
	parser := NewParser(lexer)

	file, err := parser.ParseFile()
	if err != nil {
		return nil, err
	}

	gen := NewGenerator()
	gen.SkipImports = skipImports
	return gen.Generate(file, filename)
}

// GenerateToBuffer generates code and writes it to the buffer.
// This avoids an extra allocation compared to Generate().
func (g *Generator) GenerateToBuffer(buf *bytes.Buffer, file *File, sourceFile string) error {
	data, err := g.Generate(file, sourceFile)
	if err != nil {
		return err
	}
	buf.Write(data)
	return nil
}

// generateStateBindings generates Bind() calls for reactive state bindings.
// This is called after all elements are created so the element variables exist.
func (g *Generator) generateStateBindings() {
	if len(g.stateBindings) == 0 {
		return
	}

	g.writeln("")
	g.writeln("// State bindings")

	// Build a map of state variable names to their types
	stateTypes := make(map[string]string)
	for _, sv := range g.stateVars {
		stateTypes[sv.Name] = sv.Type
	}

	for _, binding := range g.stateBindings {
		g.generateBinding(binding, stateTypes)
	}
}

// generateBinding generates a Bind() call for a single state binding.
func (g *Generator) generateBinding(b StateBinding, stateTypes map[string]string) {
	if len(b.StateVars) == 0 {
		return
	}

	// Determine the setter method based on attribute
	setter := g.getSetterForAttribute(b.Attribute)
	if setter == "" {
		return
	}

	if len(b.StateVars) == 1 {
		// Single state variable - direct binding
		stateName := b.StateVars[0]
		stateType := stateTypes[stateName]
		g.writef("%s.Bind(func(_ %s) {\n", stateName, stateType)
		g.indent++
		g.writef("%s.%s(%s)\n", b.ElementName, setter, b.Expr)
		g.indent--
		g.writeln("})")
	} else {
		// Multiple state variables - shared update function
		updateFn := fmt.Sprintf("__update_%s", b.ElementName)
		g.writef("%s := func() { %s.%s(%s) }\n", updateFn, b.ElementName, setter, b.Expr)
		for _, stateName := range b.StateVars {
			stateType := stateTypes[stateName]
			g.writef("%s.Bind(func(_ %s) { %s() })\n", stateName, stateType, updateFn)
		}
	}
}

// getSetterForAttribute returns the element setter method for a given attribute.
func (g *Generator) getSetterForAttribute(attr string) string {
	switch attr {
	case "text":
		return "SetText"
	case "class":
		// Note: class attribute bindings would need SetClass or similar
		// For now, we don't support dynamic class bindings since element
		// doesn't have a SetClass method. This is a future enhancement.
		return ""
	default:
		return ""
	}
}