gitstack

grindlemire/go-tui code browser

6.0 KB Go 257 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
package lsp

import (
	"path/filepath"
	"sync"

	"github.com/grindlemire/go-tui/internal/lsp/provider"
	"github.com/grindlemire/go-tui/internal/tuigen"
)

// Document represents an open .gsx file with its parsed state.
type Document struct {
	URI     string
	Content string
	Version int
	AST     *tuigen.File
	Errors  []*tuigen.Error
}

// DocumentManager tracks all open documents.
type DocumentManager struct {
	mu   sync.RWMutex
	docs map[string]*Document
}

// NewDocumentManager creates a new document manager.
func NewDocumentManager() *DocumentManager {
	return &DocumentManager{
		docs: make(map[string]*Document),
	}
}

// Open opens a new document and parses it.
func (dm *DocumentManager) Open(uri, content string, version int) *Document {
	dm.mu.Lock()
	defer dm.mu.Unlock()

	doc := &Document{
		URI:     uri,
		Content: content,
		Version: version,
	}

	dm.parseDocument(doc)
	dm.docs[uri] = doc
	return doc
}

// Update updates an existing document with new content.
func (dm *DocumentManager) Update(uri, content string, version int) *Document {
	dm.mu.Lock()
	defer dm.mu.Unlock()

	doc, ok := dm.docs[uri]
	if !ok {
		// Document wasn't open, open it
		doc = &Document{
			URI:     uri,
			Content: content,
			Version: version,
		}
		dm.docs[uri] = doc
	} else {
		doc.Content = content
		doc.Version = version
	}

	dm.parseDocument(doc)
	return doc
}

// Close closes a document.
func (dm *DocumentManager) Close(uri string) {
	dm.mu.Lock()
	defer dm.mu.Unlock()
	delete(dm.docs, uri)
}

// Get retrieves a document by URI.
func (dm *DocumentManager) Get(uri string) *Document {
	dm.mu.RLock()
	defer dm.mu.RUnlock()
	return dm.docs[uri]
}

// All returns all open documents.
func (dm *DocumentManager) All() []*Document {
	dm.mu.RLock()
	defer dm.mu.RUnlock()

	docs := make([]*Document, 0, len(dm.docs))
	for _, doc := range dm.docs {
		docs = append(docs, doc)
	}
	return docs
}

// parseDocument parses the document content and updates AST/Errors.
func (dm *DocumentManager) parseDocument(doc *Document) {
	// Extract filename from URI for error reporting
	filename := uriToPath(doc.URI)

	lexer := tuigen.NewLexer(filename, doc.Content)
	parser := tuigen.NewParser(lexer)
	ast, err := parser.ParseFile()

	doc.AST = ast

	// Collect errors
	doc.Errors = nil
	if err != nil {
		if errList, ok := err.(*tuigen.ErrorList); ok {
			doc.Errors = errList.Errors()
		} else if tuiErr, ok := err.(*tuigen.Error); ok {
			doc.Errors = []*tuigen.Error{tuiErr}
		}
	}

	// Run analyzer to collect semantic errors (including Tailwind class validation)
	if ast != nil {
		analyzer := tuigen.NewAnalyzer()
		analyzer.SetPackageContext(dm.buildPackageContext(doc))
		if analyzerErr := analyzer.Analyze(ast); analyzerErr != nil {
			if errList, ok := analyzerErr.(*tuigen.ErrorList); ok {
				doc.Errors = append(doc.Errors, errList.Errors()...)
			} else if tuiErr, ok := analyzerErr.(*tuigen.Error); ok {
				doc.Errors = append(doc.Errors, tuiErr)
			}
		}
	}
}

// buildPackageContext collects sibling declarations for cross-file collision
// detection. Open sibling .gsx documents contribute their in-memory ASTs
// (unsaved edits included); everything else comes from disk. Callers must
// hold dm.mu.
func (dm *DocumentManager) buildPackageContext(doc *Document) *tuigen.PackageContext {
	ctx := tuigen.NewPackageContext()

	path := uriToPath(doc.URI)
	dir := filepath.Dir(path)

	// Sibling documents open in the editor: use their parsed ASTs and note
	// their filenames so the disk scan skips the stale on-disk copies.
	openSiblings := make(map[string]bool)
	for uri, other := range dm.docs {
		if uri == doc.URI {
			continue
		}
		otherPath := uriToPath(uri)
		if filepath.Dir(otherPath) != dir {
			continue
		}
		openSiblings[filepath.Base(otherPath)] = true
		if other.AST != nil {
			ctx.AddGSXFile(other.AST)
		}
	}

	self := filepath.Base(path)
	ctx.AddDirectory(dir, func(filename string) bool {
		return filename == self || openSiblings[filename]
	})
	return ctx
}

// uriToPath converts a file:// URI to a file path.
func uriToPath(uri string) string {
	// Simple conversion - strip file:// prefix
	const prefix = "file://"
	if len(uri) > len(prefix) && uri[:len(prefix)] == prefix {
		return uri[len(prefix):]
	}
	return uri
}

// Position, Range, and Location are type aliases for the canonical definitions
// in the provider package, eliminating duplicate type definitions.
type (
	Position = provider.Position
	Range    = provider.Range
	Location = provider.Location
)

// PositionToOffset converts a Position to a byte offset in the content.
func PositionToOffset(content string, pos Position) int {
	line := 0
	offset := 0

	for i, ch := range content {
		if line == pos.Line {
			// Found the line, now count characters
			charCount := 0
			for j := i; j < len(content); j++ {
				if charCount == pos.Character {
					return j
				}
				if content[j] == '\n' {
					break
				}
				charCount++
			}
			return i + pos.Character
		}
		if ch == '\n' {
			line++
		}
		offset = i + 1
	}

	return offset
}

// OffsetToPosition converts a byte offset to a Position.
func OffsetToPosition(content string, offset int) Position {
	line := 0
	col := 0

	for i := 0; i < offset && i < len(content); i++ {
		if content[i] == '\n' {
			line++
			col = 0
		} else {
			col++
		}
	}

	return Position{Line: line, Character: col}
}

// TuigenPosToRange converts a tuigen.Position to an LSP Range.
// tuigen positions are 1-indexed, LSP positions are 0-indexed.
func TuigenPosToRange(pos tuigen.Position, length int) Range {
	start := Position{
		Line:      pos.Line - 1,
		Character: pos.Column - 1,
	}
	end := Position{
		Line:      pos.Line - 1,
		Character: pos.Column - 1 + length,
	}
	return Range{Start: start, End: end}
}

// TuigenPosToRangeWithEnd converts start and end tuigen.Positions to an LSP Range.
// tuigen positions are 1-indexed, LSP positions are 0-indexed.
func TuigenPosToRangeWithEnd(startPos, endPos tuigen.Position) Range {
	start := Position{
		Line:      startPos.Line - 1,
		Character: startPos.Column - 1,
	}
	end := Position{
		Line:      endPos.Line - 1,
		Character: endPos.Column - 1,
	}
	return Range{Start: start, End: end}
}