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"
)
type Generator struct {
buf bytes.Buffer
indent int
varCounter int
sourceFile string
refs []RefInfo
componentVars []componentVarEntry
stateVars []StateVar
stateBindings []StateBinding
eventsVars []EventsVar
componentExprFields []string
condCounter int
loopCounter int
mountIndex int
currentReceiver string
loopIndexStack []string
mountKeyParts []mountKeySegment
fileDecls []*GoDecl
fileFuncs []*GoFunc
pkgCtx *PackageContext
SkipImports bool
sourceMap *SourceMap
currentLine int
functionTempls map[string]bool
tuiAlias string
isTuiPackage bool
}
type componentVarEntry struct {
name string
componentName string
inConditional bool
inForLoop bool
}
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"
}
func NewGenerator() *Generator {
return &Generator{}
}
func (g *Generator) SetPackageContext(ctx *PackageContext) {
g.pkgCtx = ctx
}
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
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")
g.generateHeader()
g.generatePackage(file.Package)
g.generateImports(file.Imports)
firstContentLine := g.currentLine
g.fileDecls = file.Decls
g.fileFuncs = file.Funcs
g.functionTempls = make(map[string]bool)
for _, comp := range file.Components {
if comp.Receiver == "" {
g.functionTempls[comp.Name] = true
}
}
for _, decl := range file.Decls {
g.generateGoDecl(decl)
}
for _, fn := range file.Funcs {
g.generateGoFunc(fn)
}
for _, comp := range file.Components {
g.generateComponent(comp)
}
g.generateInterfaceChecks(file)
if g.SkipImports {
return format.Source(g.buf.Bytes())
}
preOutput := g.buf.Bytes()
postOutput, err := imports.Process(g.sourceFile, preOutput, nil)
if err != nil {
return nil, err
}
g.adjustSourceMapForGoimports(preOutput, postOutput, firstContentLine)
return postOutput, nil
}
func (g *Generator) adjustSourceMapForGoimports(pre, post []byte, firstContentLine int) {
postContentStart := findFirstContentLineAfterImports(post)
lineShift := postContentStart - firstContentLine
if lineShift == 0 {
return
}
for i := range g.sourceMap.Mappings {
if g.sourceMap.Mappings[i].GoLine >= firstContentLine {
g.sourceMap.Mappings[i].GoLine += lineShift
}
}
}
func findFirstContentLineAfterImports(code []byte) int {
lines := bytes.Split(code, []byte("\n"))
inImportBlock := false
importBlockEnded := false
for i, line := range lines {
trimmed := bytes.TrimSpace(line)
if bytes.HasPrefix(trimmed, []byte("import (")) {
inImportBlock = true
continue
}
if inImportBlock && len(trimmed) == 1 && trimmed[0] == ')' {
inImportBlock = false
importBlockEnded = true
continue
}
if bytes.HasPrefix(trimmed, []byte("import ")) && !bytes.HasPrefix(trimmed, []byte("import (")) {
importBlockEnded = true
continue
}
if importBlockEnded && len(trimmed) > 0 {
return i
}
}
return len(lines)
}
func (g *Generator) GetSourceMap() *SourceMap {
return g.sourceMap
}
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("")
}
func (g *Generator) generatePackage(pkg string) {
g.writef("package %s\n\n", pkg)
}
func (g *Generator) generateImports(imports []Import) {
if len(imports) == 0 {
g.writeln("import (")
g.indent++
g.writeln(`tui "github.com/grindlemire/go-tui"`)
g.indent--
g.writeln(")")
g.writeln("")
return
}
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)
}
}
if !hasTui {
g.writeln("")
g.writeln(`tui "github.com/grindlemire/go-tui"`)
}
g.indent--
g.writeln(")")
g.writeln("")
}
func (g *Generator) nextVar() string {
name := fmt.Sprintf("__tui_%d", g.varCounter)
g.varCounter++
return name
}
func (g *Generator) nextCondVar() string {
name := fmt.Sprintf("__cond_%d", g.condCounter)
g.condCounter++
return name
}
func (g *Generator) nextLoopVar() string {
name := fmt.Sprintf("__loop_%d", g.loopCounter)
g.loopCounter++
return 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
}
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]
}
}
type mountKeySegment struct {
expr string
fromLoop bool
}
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 }
}
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, ", "))
}
func (g *Generator) stateNameSet() map[string]bool {
m := make(map[string]bool)
for _, sv := range g.stateVars {
m[sv.Name] = true
}
return m
}
func (g *Generator) write(s string) {
g.buf.WriteString(s)
for _, c := range s {
if c == '\n' {
g.currentLine++
}
}
}
func (g *Generator) writef(format string, args ...any) {
g.writeIndent()
s := fmt.Sprintf(format, args...)
g.buf.WriteString(s)
for _, c := range s {
if c == '\n' {
g.currentLine++
}
}
}
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++
}
func (g *Generator) writeIndent() {
for i := 0; i < g.indent; i++ {
g.buf.WriteByte('\t')
}
}
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
}
func ParseAndGenerate(filename, source string) ([]byte, error) {
return parseAndGenerate(filename, source, false)
}
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)
}
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
}
func (g *Generator) generateStateBindings() {
if len(g.stateBindings) == 0 {
return
}
g.writeln("")
g.writeln("// State bindings")
stateTypes := make(map[string]string)
for _, sv := range g.stateVars {
stateTypes[sv.Name] = sv.Type
}
for _, binding := range g.stateBindings {
g.generateBinding(binding, stateTypes)
}
}
func (g *Generator) generateBinding(b StateBinding, stateTypes map[string]string) {
if len(b.StateVars) == 0 {
return
}
setter := g.getSetterForAttribute(b.Attribute)
if setter == "" {
return
}
if len(b.StateVars) == 1 {
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 {
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)
}
}
}
func (g *Generator) getSetterForAttribute(attr string) string {
switch attr {
case "text":
return "SetText"
case "class":
return ""
default:
return ""
}
}
|