gitstack

grindlemire/go-tui code browser

6.4 KB Go 241 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
package tuigen

import (
	"unicode"
	"unicode/utf8"
)

// skipWhitespaceAndCollectComments skips spaces, tabs, and collects comments (but not newlines).
func (l *Lexer) skipWhitespaceAndCollectComments() {
	for {
		switch l.ch {
		case ' ', '\t', '\r':
			l.readChar()
		case '/':
			if l.peekChar() == '/' {
				// Line comment: collect it
				l.collectLineComment()
			} else if l.peekChar() == '*' {
				// Block comment: collect it
				l.collectBlockComment()
			} else {
				return
			}
		default:
			return
		}
	}
}

// collectLineComment reads a // comment and adds it to pendingComments.
func (l *Lexer) collectLineComment() {
	startPos := l.pos
	startLine := l.line
	startCol := l.column

	// Check if there was a blank line before this comment
	blankLineBefore := l.hadBlankLineBefore(startLine)

	// Read until end of line or EOF
	for l.ch != '\n' && l.ch != 0 {
		l.readChar()
	}

	comment := &Comment{
		Text:            l.source[startPos:l.pos],
		Position:        Position{File: l.filename, Line: startLine, Column: startCol},
		EndLine:         l.line,
		EndCol:          l.column,
		IsBlock:         false,
		BlankLineBefore: blankLineBefore,
	}
	l.pendingComments = append(l.pendingComments, comment)
	l.lastCommentEndLine = l.line
}

// collectBlockComment reads a /* */ comment and adds it to pendingComments.
func (l *Lexer) collectBlockComment() {
	startPos := l.pos
	startLine := l.line
	startCol := l.column

	// Check if there was a blank line before this comment
	blankLineBefore := l.hadBlankLineBefore(startLine)

	l.readChar() // skip /
	l.readChar() // skip *

	for {
		if l.ch == 0 {
			l.errors.AddError(Position{File: l.filename, Line: startLine, Column: startCol}, "unterminated block comment")
			return
		}
		if l.ch == '*' && l.peekChar() == '/' {
			l.readChar() // skip *
			l.readChar() // skip /
			break
		}
		l.readChar()
	}

	comment := &Comment{
		Text:            l.source[startPos:l.pos],
		Position:        Position{File: l.filename, Line: startLine, Column: startCol},
		EndLine:         l.line,
		EndCol:          l.column,
		IsBlock:         true,
		BlankLineBefore: blankLineBefore,
	}
	l.pendingComments = append(l.pendingComments, comment)
	l.lastCommentEndLine = l.line
}

// hadBlankLineBefore checks if there was a blank line before the given line.
// This only returns true if there's a previous comment (in pending list or recently consumed)
// and there's a blank line between that comment and the current line.
func (l *Lexer) hadBlankLineBefore(currentLine int) bool {
	// Check against the last pending comment first
	if len(l.pendingComments) > 0 {
		lastComment := l.pendingComments[len(l.pendingComments)-1]
		return currentLine > lastComment.EndLine+1
	}

	// Check against the last consumed comment (if any)
	if l.lastCommentEndLine > 0 {
		return currentLine > l.lastCommentEndLine+1
	}

	return false
}

// ConsumeComments returns and clears pending comments.
// Called by parser after each node is parsed.
func (l *Lexer) ConsumeComments() []*Comment {
	comments := l.pendingComments
	l.pendingComments = nil
	return comments
}

// readIdentifier reads an identifier or keyword.
func (l *Lexer) readIdentifier() Token {
	startPos := l.pos
	for isLetter(l.ch) || isDigit(l.ch) {
		l.readChar()
	}
	literal := l.source[startPos:l.pos]
	tokenType := LookupIdent(literal)
	return l.makeToken(tokenType, literal)
}

// readAtKeyword reads a @-prefixed DSL keyword.
func (l *Lexer) readAtKeyword() Token {
	l.readChar() // consume @

	// Save the position of the keyword start (after @) for deprecated keywords
	kwLine := l.line
	kwColumn := l.column
	kwStartPos := l.pos

	startPos := l.pos
	for isLetter(l.ch) {
		l.readChar()
	}
	keyword := l.source[startPos:l.pos]

	switch keyword {
	case "for", "if", "else":
		// Record diagnostic error (shows as squiggly underline in LSP).
		// Still emit the correct bare token so the parser can continue.
		l.errors.AddErrorf(l.position(), "@%s is no longer supported, use bare \"%s\" instead", keyword, keyword)
		l.tokenLine = kwLine
		l.tokenColumn = kwColumn
		l.tokenStartPos = kwStartPos
		switch keyword {
		case "for":
			return l.makeToken(TokenFor, "for")
		case "if":
			return l.makeToken(TokenIf, "if")
		default: // "else"
			return l.makeToken(TokenElse, "else")
		}
	case "let":
		l.errors.AddErrorf(l.position(), "@let is no longer supported, use \"name := <element>\" instead")
		return l.makeToken(TokenError, "@let")
	default:
		if len(keyword) > 0 {
			firstRune, _ := utf8.DecodeRuneInString(keyword)
			if unicode.IsUpper(firstRune) {
				// Uppercase: component function call @Header()
				return l.makeToken(TokenAtCall, keyword)
			}
			// Lowercase: component expression @c.textarea (renders a Component)
			// Continue reading the full expression (field access, etc.)
			for l.ch == '.' || isLetter(l.ch) || isDigit(l.ch) {
				l.readChar()
			}
			expr := l.source[startPos:l.pos]
			return l.makeToken(TokenAtExpr, expr)
		}
		l.errors.AddErrorf(l.position(), "unknown @ keyword: @%s", keyword)
		return l.makeToken(TokenError, "@"+keyword)
	}
}

// isLetter returns true if the rune is a letter or underscore.
func isLetter(ch rune) bool {
	return unicode.IsLetter(ch) || ch == '_'
}

// isDigit returns true if the rune is a digit.
func isDigit(ch rune) bool {
	return unicode.IsDigit(ch)
}

// CurrentChar returns the current character being examined.
// Used by the parser to check if we're at a { for Go expressions.
func (l *Lexer) CurrentChar() rune {
	return l.ch
}

// SkipWhitespace is a public method for the parser to skip whitespace and collect comments.
func (l *Lexer) SkipWhitespace() {
	l.skipWhitespaceAndCollectComments()
}

// SourcePos returns the current position in the source string.
// Used by the parser to mark start positions for raw source capture.
func (l *Lexer) SourcePos() int {
	return l.pos
}

// PositionAt converts a byte offset in the source to a 1-based line/column Position.
func (l *Lexer) PositionAt(offset int) Position {
	line := 1
	col := 1
	for i := 0; i < offset && i < len(l.source); {
		r, size := utf8.DecodeRuneInString(l.source[i:])
		if r == '\n' {
			line++
			col = 1
		} else {
			col++
		}
		i += size
	}
	return Position{Line: line, Column: col}
}

// SourceRange extracts a substring of the original source from start to end positions.
// Used by the parser to capture raw Go code without tokenization.
func (l *Lexer) SourceRange(start, end int) string {
	if start < 0 {
		start = 0
	}
	if end > len(l.source) {
		end = len(l.source)
	}
	if start >= end {
		return ""
	}
	return l.source[start:end]
}