all repos

clerk @ 065541fce45b81eae307599c89f832163785a8cc

missing tooling for ledger/hledger

clerk/internal/lsp/textdocument_semantic.go (view raw)

Oleksandr Smirnov Oleksandr Smirnov
olexsmir@gmail.com
lsp: move code around, 2 months ago
1
package lsp
2
3
import (
4
	"context"
5
	"slices"
6
	"unicode/utf8"
7
8
	"go.lsp.dev/protocol"
9
	"go.lsp.dev/uri"
10
11
	"olexsmir.xyz/clerk/internal/lsp/lsputil"
12
	"olexsmir.xyz/clerk/journal/ast"
13
	"olexsmir.xyz/clerk/journal/lexer"
14
	"olexsmir.xyz/clerk/journal/token"
15
)
16
17
func (s *server) SemanticTokensFull(ctx context.Context, params *protocol.SemanticTokensParams) (*protocol.SemanticTokens, error) {
18
	if !s.semanticHighlightingEnabled() {
19
		return &protocol.SemanticTokens{}, nil
20
	}
21
22
	tokens, ok := s.tokensForDoc(params.TextDocument.URI)
23
	if !ok {
24
		return &protocol.SemanticTokens{}, nil
25
	}
26
	return &protocol.SemanticTokens{Data: encodeSemTokens(tokens)}, nil
27
}
28
29
func (s *server) SemanticTokensRange(ctx context.Context, params *protocol.SemanticTokensRangeParams) (*protocol.SemanticTokens, error) {
30
	if !s.semanticHighlightingEnabled() {
31
		return &protocol.SemanticTokens{}, nil
32
	}
33
34
	tokens, ok := s.tokensForDoc(params.TextDocument.URI)
35
	if !ok {
36
		return &protocol.SemanticTokens{}, nil
37
	}
38
	start := int(params.Range.Start.Line)
39
	end := int(params.Range.End.Line)
40
	var filtered []semanticToken
41
	for _, t := range tokens {
42
		if t.line >= uint32(start) && t.line <= uint32(end) {
43
			filtered = append(filtered, t)
44
		}
45
	}
46
	return &protocol.SemanticTokens{Data: encodeSemTokens(filtered)}, nil
47
}
48
49
func (s *server) tokensForDoc(doc uri.URI) ([]semanticToken, bool) {
50
	s.mu.Lock()
51
	defer s.mu.Unlock()
52
	st, ok := s.openDocs[doc]
53
	if !ok {
54
		return nil, false
55
	}
56
	if st.semTokens != nil {
57
		return st.semTokens, true
58
	}
59
	st.semTokens = tokenizeForSemantics(st.text, parseJournalStr(st.text))
60
	s.openDocs[doc] = st
61
	return st.semTokens, true
62
}
63
64
// Implementation
65
66
const (
67
	semDirective = iota
68
	semDate
69
	semAccount
70
	semCommodity
71
	semAmount
72
	semStatus
73
	semComment
74
	semString
75
	semOperator
76
	semProperty
77
)
78
79
var tokenTypeStrings = []string{
80
	string(protocol.SemanticTokenTypesKeyword),   // directive
81
	string(protocol.SemanticTokenTypesClass),     // date
82
	string(protocol.SemanticTokenTypesNamespace), // account
83
	string(protocol.SemanticTokenTypesType),      // commodity
84
	string(protocol.SemanticTokenTypesNumber),    // amount
85
	string(protocol.SemanticTokenTypesOperator),  // status
86
	string(protocol.SemanticTokenTypesComment),   // comment
87
	string(protocol.SemanticTokenTypesString),    // string
88
	string(protocol.SemanticTokenTypesOperator),  // operator
89
	string(protocol.SemanticTokenTypesProperty),  // property
90
}
91
92
const (
93
	modifierAbstract = 1 << 0 // virtual account
94
	modifierNegative = 1 << 1 // negative amount
95
)
96
97
var modifierStrings = []string{
98
	"abstract", // bit 0
99
	"negative", // bit 1
100
}
101
102
func getSemanticTokensLegend() protocol.SemanticTokensLegend {
103
	return protocol.SemanticTokensLegend{
104
		TokenTypes:     tokenTypeStrings,
105
		TokenModifiers: modifierStrings,
106
	}
107
}
108
109
type semanticToken struct {
110
	line, col uint32 // 0-based
111
	length    uint32
112
	tokenType uint32
113
	modifiers uint32
114
}
115
116
func tokenizeForSemantics(content string, j *ast.Journal) []semanticToken {
117
	var raw []rawSpan
118
	emit := func(s token.Span, tokType, mods uint32) {
119
		if s.Start.Offset >= s.End.Offset {
120
			return
121
		}
122
		raw = append(raw, rawSpan{s, tokType, mods})
123
	}
124
	if j == nil || len(j.Errors) > 0 {
125
		semLexerFallback(content, emit)
126
	} else {
127
		for _, e := range j.Entries {
128
			visitEntry(content, e, emit)
129
		}
130
	}
131
	return rawToSemanticTokens(content, raw)
132
}
133
134
// rawSpan is a source span tagged with semantic token
135
type rawSpan struct {
136
	span      token.Span
137
	tok, mods uint32
138
}
139
140
func rawToSemanticTokens(content string, raw []rawSpan) []semanticToken {
141
	if len(raw) == 0 {
142
		return nil
143
	}
144
	slices.SortFunc(raw, func(a, b rawSpan) int { return a.span.Start.Offset - b.span.Start.Offset })
145
	out := make([]semanticToken, len(raw))
146
	line, col, cursor := 0, 0, 0
147
	advance := func(end int) {
148
		for cursor < end {
149
			r, size := utf8.DecodeRuneInString(content[cursor:])
150
			if r == utf8.RuneError && size <= 1 {
151
				break
152
			}
153
			if r == '\r' {
154
				cursor += size
155
				if cursor < len(content) && content[cursor] == '\n' {
156
					cursor++
157
				}
158
				line++
159
				col = 0
160
				continue
161
			}
162
			if r == '\n' {
163
				cursor += size
164
				line++
165
				col = 0
166
				continue
167
			}
168
			cursor += size
169
			col += utf16Units(r)
170
		}
171
	}
172
	for i, t := range raw {
173
		if cursor < t.span.Start.Offset {
174
			advance(t.span.Start.Offset)
175
		}
176
		out[i] = semanticToken{
177
			line:      uint32(line),
178
			col:       uint32(col),
179
			length:    uint32(lsputil.Utf16Len(content, t.span.Start.Offset, t.span.End.Offset)),
180
			tokenType: t.tok,
181
			modifiers: t.mods,
182
		}
183
		advance(t.span.End.Offset)
184
	}
185
	return out
186
}
187
188
func utf16Units(r rune) int {
189
	if r >= 0x10000 && r <= 0x10FFFF {
190
		return 2
191
	}
192
	return 1
193
}
194
195
func visitEntry(content string, e ast.Entry, emit semEmitFn) {
196
	switch e := e.(type) {
197
	case *ast.Transaction:
198
		visitTransaction(content, e, emit)
199
	case *ast.PeriodicTransaction:
200
		visitPeriodicTransaction(content, e, emit)
201
	case *ast.AutomatedTransaction:
202
		visitAutomatedTransaction(content, e, emit)
203
	case *ast.AccountDirective:
204
		emit(directiveKeyword(e.Span, "account"), semDirective, 0)
205
		emit(e.Account.Span, semAccount, 0)
206
		if e.Comment != nil {
207
			emit(e.Comment.Span, semComment, 0)
208
		}
209
	case *ast.CommodityDirective:
210
		emit(directiveKeyword(e.Span, "commodity"), semDirective, 0)
211
		if e.Format.Span.End.Offset > 0 {
212
			semEmitAmount(content, &e.Format, emit)
213
		} else if e.CommoditySpan.Start.Offset > 0 && e.CommoditySpan.End.Offset > 0 {
214
			emit(e.CommoditySpan, semCommodity, 0)
215
		}
216
		if e.Comment != nil {
217
			emit(e.Comment.Span, semComment, 0)
218
		}
219
	case *ast.IncludeDirective:
220
		emitDirective(content, e.Span, len("include"), semString, e.Comment, emit)
221
	case *ast.PayeeDirective:
222
		emitDirective(content, e.Span, len("payee"), semProperty, e.Comment, emit)
223
	case *ast.TagDirective:
224
		emitDirective(content, e.Span, len("tag"), semProperty, e.Comment, emit)
225
	case *ast.AliasDirective:
226
		emit(directiveKeyword(e.Span, "alias"), semDirective, 0)
227
		emit(e.From.Span, semAccount, 0)
228
		if op, ok := betweenSpan(content, e.Span.Start.File, e.From.Span.End.Offset, e.To.Span.Start.Offset); ok {
229
			emit(op, semOperator, 0)
230
		}
231
		emit(e.To.Span, semAccount, 0)
232
		if e.Comment != nil {
233
			emit(e.Comment.Span, semComment, 0)
234
		}
235
	case *ast.YearDirective:
236
		kwLen := len("year")
237
		if content[e.Span.Start.Offset] == 'Y' {
238
			kwLen = 1
239
		}
240
		emitDirective(content, e.Span, kwLen, semProperty, e.Comment, emit)
241
	case *ast.DecimalMarkDirective:
242
		emitDirective(content, e.Span, len("decimal-mark"), semProperty, e.Comment, emit)
243
	case *ast.DefaultCommodityDirective:
244
		emit(directiveKeyword(e.Span, "D"), semDirective, 0)
245
		semEmitAmount(content, &e.Amount, emit)
246
		if e.Comment != nil {
247
			emit(e.Comment.Span, semComment, 0)
248
		}
249
	case *ast.MarketPriceDirective:
250
		emit(directiveKeyword(e.Span, "P"), semDirective, 0)
251
		emit(e.DateTime.Date.Span, semDate, 0)
252
		if e.DateTime.Time != nil {
253
			emit(e.DateTime.Time.Span, semDate, 0)
254
		}
255
		// commodity: text between the date (or time) and the amount
256
		commStart := e.DateTime.Date.Span.End.Offset
257
		if e.DateTime.Time != nil {
258
			commStart = e.DateTime.Time.Span.End.Offset
259
		}
260
		if comm, ok := betweenSpan(content, e.Span.Start.File, commStart, e.Amount.Span.Start.Offset); ok {
261
			emit(comm, semCommodity, 0)
262
		}
263
		semEmitAmount(content, &e.Amount, emit)
264
		if e.Comment != nil {
265
			emit(e.Comment.Span, semComment, 0)
266
		}
267
	case *ast.ConversionDirective:
268
		emit(directiveKeyword(e.Span, "C"), semDirective, 0)
269
		semEmitAmount(content, &e.From, emit)
270
		// = operator: text between the two amounts
271
		if op, ok := betweenSpan(content, e.Span.Start.File, e.From.Span.End.Offset, e.To.Span.Start.Offset); ok {
272
			emit(op, semOperator, 0)
273
		}
274
		semEmitAmount(content, &e.To, emit)
275
		if e.Comment != nil {
276
			emit(e.Comment.Span, semComment, 0)
277
		}
278
	case *ast.Comment:
279
		emit(e.Span, semComment, 0)
280
	case *ast.CommentBlockDirective:
281
		emit(e.Span, semComment, 0)
282
	case *ast.IgnoredDirective:
283
		emitDirective(content, e.Span, len("N"), semProperty, e.Comment, emit)
284
	case *ast.ApplyDirective:
285
		emitDirective(content, e.Span, len("apply"), semProperty, e.Comment, emit)
286
	case *ast.EndDirective:
287
		emitDirective(content, e.Span, len("end"), semProperty, e.Comment, emit)
288
	case *ast.BlankLine:
289
	}
290
}
291
292
func visitTransaction(content string, t *ast.Transaction, emit semEmitFn) {
293
	emit(t.Date.Span, semDate, 0)
294
	if t.SecondDate != nil {
295
		emit(t.SecondDate.Span, semDate, 0)
296
	}
297
	if t.Status.Value != ast.StatusNone {
298
		emit(t.Status.Span, semStatus, 0)
299
	}
300
	if t.Code != nil {
301
		emit(t.Code.Span, semString, 0)
302
	}
303
	if t.Payee != nil {
304
		emit(t.Payee.Span, semProperty, 0)
305
	}
306
	if t.Note != nil {
307
		emit(t.Note.Span, semProperty, 0)
308
	}
309
	if t.Comment != nil {
310
		emit(t.Comment.Span, semComment, 0)
311
	}
312
	for i := range t.HeaderComments {
313
		emit(t.HeaderComments[i].Span, semComment, 0)
314
	}
315
	for _, p := range t.Postings {
316
		visitPosting(content, p, emit)
317
	}
318
}
319
320
func visitPeriodicTransaction(content string, pt *ast.PeriodicTransaction, emit semEmitFn) {
321
	// ~ operator is at the start of the period span
322
	emit(offsetSpan(pt.Span.Start.File, pt.Span.Start.Offset, pt.Span.Start.Offset+1), semOperator, 0)
323
324
	// The period span covers the whole expr, including any "from ... to ..." dates
325
	if pt.Period.Span.End.Offset > pt.Period.Span.Start.Offset {
326
		var dates []*ast.Date
327
		if pt.Period.From != nil {
328
			dates = append(dates, pt.Period.From)
329
		}
330
		if pt.Period.To != nil {
331
			dates = append(dates, pt.Period.To)
332
		}
333
		pos := pt.Period.Span.Start.Offset
334
		for _, d := range dates {
335
			if d.Span.Start.Offset > pos {
336
				emit(offsetSpan(pt.Period.Span.Start.File, pos, d.Span.Start.Offset), semProperty, 0)
337
			}
338
			emit(d.Span, semDate, 0)
339
			pos = d.Span.End.Offset
340
		}
341
		if pos < pt.Period.Span.End.Offset {
342
			emit(offsetSpan(pt.Period.Span.Start.File, pos, pt.Period.Span.End.Offset), semProperty, 0)
343
		}
344
	}
345
	if pt.Description != nil {
346
		emit(pt.Description.Span, semProperty, 0)
347
	}
348
	if pt.Comment != nil {
349
		emit(pt.Comment.Span, semComment, 0)
350
	}
351
	for i := range pt.HeaderComments {
352
		emit(pt.HeaderComments[i].Span, semComment, 0)
353
	}
354
	for _, p := range pt.Postings {
355
		visitPosting(content, p, emit)
356
	}
357
}
358
359
func visitAutomatedTransaction(content string, at *ast.AutomatedTransaction, emit semEmitFn) {
360
	// = operator is at the start of the expression span
361
	emit(offsetSpan(at.Span.Start.File, at.Span.Start.Offset, at.Span.Start.Offset+1), semOperator, 0)
362
363
	if at.Expr.Value != "" {
364
		emit(at.Expr.Span, semString, 0)
365
	}
366
	if at.Comment != nil {
367
		emit(at.Comment.Span, semComment, 0)
368
	}
369
	for i := range at.HeaderComments {
370
		emit(at.HeaderComments[i].Span, semComment, 0)
371
	}
372
	for _, p := range at.Postings {
373
		visitPosting(content, p, emit)
374
	}
375
}
376
377
func visitPosting(content string, p *ast.Posting, emit semEmitFn) {
378
	if p.Status.Value != ast.StatusNone {
379
		emit(p.Status.Span, semStatus, 0)
380
	}
381
382
	// virtual brackets
383
	if p.Type == ast.PostingVirtualUnbalanced || p.Type == ast.PostingVirtualBalanced {
384
		// opening bracket
385
		for off := p.Span.Start.Offset; off < p.Account.Span.Start.Offset && off < p.Span.End.Offset; off++ {
386
			if content[off] == '(' || content[off] == '[' {
387
				brSpan := token.Span{Start: offsetPos(p.Span.Start.File, off), End: offsetPos(p.Span.Start.File, off+1)}
388
				emit(brSpan, semOperator, modifierAbstract)
389
				break
390
			}
391
		}
392
		// closing bracket
393
		for off := p.Account.Span.End.Offset; off < p.Span.End.Offset; off++ {
394
			if content[off] == ')' || content[off] == ']' {
395
				brSpan := token.Span{Start: offsetPos(p.Span.Start.File, off), End: offsetPos(p.Span.Start.File, off+1)}
396
				emit(brSpan, semOperator, modifierAbstract)
397
				break
398
			}
399
		}
400
	}
401
402
	emit(p.Account.Span, semAccount, 0)
403
404
	if p.Amount != nil {
405
		semEmitAmount(content, p.Amount, emit)
406
	}
407
	if p.Cost != nil {
408
		semEmitCost(content, p.Cost, emit)
409
	}
410
	if p.Balance != nil {
411
		semEmitBalanceAssertion(content, p.Balance, emit)
412
	}
413
	if p.Comment != nil {
414
		emit(p.Comment.Span, semComment, 0)
415
	}
416
	for i := range p.Comments {
417
		emit(p.Comments[i].Span, semComment, 0)
418
	}
419
}
420
421
// directiveKeyword returns the span of the leading keyword on a directive line.
422
func directiveKeyword(e token.Span, kw string) token.Span {
423
	return token.Span{Start: e.Start, End: offsetPos(e.Start.File, e.Start.Offset+len(kw))}
424
}
425
426
// directiveValue returns the trimmed span of the text after the keyword end
427
// offset, up to the inline comment or the end of the line.
428
func directiveValue(content string, e token.Span, comment *ast.Comment, kwEnd int) (token.Span, bool) {
429
	end := e.End.Offset
430
	if comment != nil {
431
		end = comment.Span.Start.Offset
432
	}
433
	return betweenSpan(content, e.Start.File, kwEnd, end)
434
}
435
436
func semEmitAmount(content string, a *ast.Amount, emit semEmitFn) {
437
	if a == nil {
438
		return
439
	}
440
	hasCommodity := a.CommoditySpan.Start.Offset > 0 && a.CommoditySpan.End.Offset > 0
441
	if hasCommodity && a.CommodityPos == ast.CommodityBefore {
442
		emit(a.CommoditySpan, semCommodity, 0)
443
		semEmitQuantity(content, a, emit)
444
		return
445
	}
446
	semEmitQuantity(content, a, emit)
447
	if hasCommodity {
448
		emit(a.CommoditySpan, semCommodity, 0)
449
	}
450
}
451
452
func semEmitQuantity(content string, a *ast.Amount, emit semEmitFn) {
453
	qStart, qEnd := quantitySpan(content, a)
454
	if qEnd <= qStart {
455
		return
456
	}
457
	mods := uint32(0)
458
	if a.IsNegative {
459
		mods |= modifierNegative
460
	}
461
	emit(offsetSpan(a.Span.Start.File, qStart, qEnd), semAmount, mods)
462
}
463
464
func quantitySpan(content string, a *ast.Amount) (int, int) {
465
	start, end := a.Span.Start.Offset, a.Span.End.Offset
466
	switch {
467
	case a.Commodity == "":
468
		// bare quantity
469
	case a.CommodityPos == ast.CommodityBefore:
470
		// "$50.00" or "$   50.00": quantity follows the commodity span
471
		start = a.CommoditySpan.End.Offset
472
	default: // CommodityAfter
473
		// "50.00 USD" or "50.00     USD": quantity precedes the commodity
474
		end = a.CommoditySpan.Start.Offset
475
	}
476
	for start < end && (content[start] == ' ' || content[start] == '\t') {
477
		start++
478
	}
479
	for end > start && (content[end-1] == ' ' || content[end-1] == '\t') {
480
		end--
481
	}
482
	return start, end
483
}
484
485
type semEmitFn func(token.Span, uint32, uint32)
486
487
func emitDirective(content string, e token.Span, kwLen int, valType uint32, comment *ast.Comment, emit semEmitFn) {
488
	kwEnd := e.Start.Offset + kwLen
489
	emit(token.Span{Start: e.Start, End: offsetPos(e.Start.File, kwEnd)}, semDirective, 0)
490
	if v, ok := directiveValue(content, e, comment, kwEnd); ok {
491
		emit(v, valType, 0)
492
	}
493
	if comment != nil {
494
		emit(comment.Span, semComment, 0)
495
	}
496
}
497
498
func semEmitCost(content string, c *ast.Cost, emit semEmitFn) {
499
	if c.IsTotal {
500
		emit(token.Span{Start: c.Span.Start, End: offsetPos(c.Span.Start.File, c.Span.Start.Offset+2)}, semOperator, 0)
501
	} else {
502
		emit(token.Span{Start: c.Span.Start, End: offsetPos(c.Span.Start.File, c.Span.Start.Offset+1)}, semOperator, 0)
503
	}
504
	semEmitAmount(content, &c.Amount, emit)
505
}
506
507
func semEmitBalanceAssertion(content string, ba *ast.BalanceAssertion, emit semEmitFn) {
508
	// The operator is the run of '=', ':', '*' chars from the span start.
509
	// The ':' of ':=' precedes the '=' token, so back up one offset.
510
	opStart := ba.Span.Start.Offset
511
	if ba.IsAssignment && opStart > 0 {
512
		opStart--
513
	}
514
	opEnd := opStart
515
	for opEnd < ba.Span.End.Offset && (content[opEnd] == '=' || content[opEnd] == ':' || content[opEnd] == '*') {
516
		opEnd++
517
	}
518
	emit(token.Span{Start: offsetPos(ba.Span.Start.File, opStart), End: offsetPos(ba.Span.Start.File, opEnd)}, semOperator, 0)
519
	semEmitAmount(content, &ba.Amount, emit)
520
	if ba.Cost != nil {
521
		semEmitCost(content, ba.Cost, emit)
522
	}
523
}
524
525
// semLexerFallback produces semantic tokens using only the lexer (for unparseable documents).
526
func semLexerFallback(content string, emit semEmitFn) {
527
	l := lexer.New("", []byte(content))
528
529
	var commentStart, commentEnd int // 0 = not inside a comment line
530
	take := func(span token.Span, tokType uint32, mods uint32) {
531
		emit(span, tokType, mods)
532
	}
533
	for {
534
		tok := l.Next()
535
		if tok.Type == token.EOF {
536
			if commentStart > 0 {
537
				take(token.Span{Start: offsetPos("", commentStart), End: offsetPos("", commentEnd)}, semComment, 0)
538
			}
539
			break
540
		}
541
		if tok.Type == token.NEWLINE {
542
			if commentStart > 0 {
543
				take(token.Span{Start: offsetPos("", commentStart), End: offsetPos("", commentEnd)}, semComment, 0)
544
				commentStart, commentEnd = 0, 0
545
			}
546
			continue
547
		}
548
		if tok.Type == token.WHITESPACE || tok.Type == token.INDENT {
549
			continue
550
		}
551
		tokType := uint32(semString)
552
		if commentStart > 0 {
553
			tokType = semComment
554
			if tok.Span.End.Offset > commentEnd {
555
				commentEnd = tok.Span.End.Offset
556
			}
557
			continue
558
		}
559
		switch tok.Type {
560
		case token.SEMICOLON, token.HASH, token.PERCENT:
561
			tokType = semComment
562
			commentStart = tok.Span.Start.Offset
563
			commentEnd = tok.Span.End.Offset
564
			continue
565
		case token.STAR:
566
			tokType = semComment // * at col 0 is comment marker
567
			commentStart = tok.Span.Start.Offset
568
			commentEnd = tok.Span.End.Offset
569
			continue
570
		case token.ACCOUNT, token.COMMODITY, token.INCLUDE, token.ALIAS,
571
			token.PAYEE, token.TAG, token.APPLY, token.END, token.COMMENTKW,
572
			token.YEAR, token.DECIMALMARK, token.D, token.P, token.N, token.C:
573
			tokType = semDirective
574
		case token.DATE:
575
			tokType = semDate
576
		case token.INT, token.DECIMAL:
577
			tokType = semAmount
578
		case token.COMMODITYMARK:
579
			tokType = semCommodity
580
		case token.BANG:
581
			tokType = semStatus
582
		case token.AT, token.ATAT, token.EQ, token.EQEQ, token.EQEQEQ, token.EQSTAR:
583
			tokType = semOperator
584
		}
585
		take(tok.Span, tokType, 0)
586
	}
587
}
588
589
func encodeSemTokens(tokens []semanticToken) []uint32 {
590
	if len(tokens) == 0 {
591
		return nil
592
	}
593
	slices.SortFunc(tokens, func(a, b semanticToken) int {
594
		if a.line != b.line {
595
			return int(a.line) - int(b.line)
596
		}
597
		return int(a.col) - int(b.col)
598
	})
599
	data := make([]uint32, 0, len(tokens)*5)
600
	var prevLine, prevCol uint32
601
	for _, t := range tokens {
602
		var deltaLine, deltaCol uint32
603
		if t.line == prevLine {
604
			deltaLine = 0
605
			deltaCol = t.col - prevCol
606
		} else {
607
			deltaLine = t.line - prevLine
608
			deltaCol = t.col
609
		}
610
		data = append(data, deltaLine, deltaCol, t.length, t.tokenType, t.modifiers)
611
		prevLine = t.line
612
		prevCol = t.col
613
	}
614
	return data
615
}
616
617
// betweenSpan returns the span of the text between two offsets, trimmed of surrounding whitespace.
618
func betweenSpan(content, file string, start, end int) (token.Span, bool) {
619
	for start < end && (content[start] == ' ' || content[start] == '\t') {
620
		start++
621
	}
622
	for end > start && (content[end-1] == ' ' || content[end-1] == '\t' || content[end-1] == '\n' || content[end-1] == '\r') {
623
		end--
624
	}
625
	if end <= start {
626
		return token.Span{}, false
627
	}
628
	return token.Span{Start: offsetPos(file, start), End: offsetPos(file, end)}, true
629
}
630
631
func offsetPos(file string, offset int) token.Pos { return token.Pos{File: file, Offset: offset} }
632
func offsetSpan(file string, start, end int) token.Span {
633
	return token.Span{Start: offsetPos(file, start), End: offsetPos(file, end)}
634
}