gitstack

grindlemire/go-tui code browser

20.8 KB Go 716 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
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
package provider

import (
	"strings"

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

// definitionProvider implements DefinitionProvider.
type definitionProvider struct {
	index        ComponentIndex
	goplsProxy   GoplsProxyAccessor
	virtualFiles VirtualFileAccessor
	docs         DocumentAccessor
}

// NewDefinitionProvider creates a new definition provider.
func NewDefinitionProvider(index ComponentIndex, proxy GoplsProxyAccessor, vf VirtualFileAccessor, docs DocumentAccessor) DefinitionProvider {
	return &definitionProvider{
		index:        index,
		goplsProxy:   proxy,
		virtualFiles: vf,
		docs:         docs,
	}
}

func (d *definitionProvider) Definition(ctx *CursorContext) ([]Location, error) {
	log.Server("Definition provider: NodeKind=%s, Word=%q, InGoExpr=%v", ctx.NodeKind, ctx.Word, ctx.InGoExpr)

	word := ctx.Word

	// Check local function definitions first (prevents gopls from
	// returning generated .go files instead of .gsx sources).
	// Skip this when inside a Go expression — gopls understands the full
	// context (e.g., field access a.category vs a standalone function call).
	if word != "" && !ctx.InGoExpr {
		funcName := strings.TrimPrefix(word, "@")
		if funcInfo, ok := d.index.LookupFunc(funcName); ok {
			log.Server("Found local function %s at %s (before gopls)", funcName, funcInfo.Location.URI)
			return []Location{funcInfo.Location}, nil
		}
	}

	if word == "" {
		// Without a word, only gopls can resolve (it works by position).
		if ctx.InGoExpr {
			locs, err := d.getGoplsDefinition(ctx)
			if err == nil && len(locs) > 0 {
				return locs, nil
			}
		}
		return nil, nil
	}

	// Dispatch based on node kind. Each case resolves using local knowledge
	// first; unresolved Go expressions fall through to the gopls fallback.
	switch ctx.NodeKind {
	case NodeKindComponentCall:
		return d.definitionComponentCall(ctx)
	case NodeKindRefAttr:
		return d.definitionRefAttr(ctx)
	case NodeKindEventHandler:
		return d.definitionEventHandler(ctx)
	case NodeKindParameter:
		return d.definitionParameter(ctx)
	case NodeKindImportPath:
		return d.definitionImport(ctx)
	case NodeKindStateAccess, NodeKindStateDecl:
		locs, err := d.definitionStateVar(ctx)
		if err == nil && len(locs) > 0 {
			return locs, nil
		}
		// Fall through to gopls for unresolved state references
	case NodeKindGoExpr:
		// Check refs in scope before deferring to gopls (which would
		// return the element tag position from generated code, not the ref site).
		if locs := d.definitionRefFromScope(ctx); len(locs) > 0 {
			return locs, nil
		}
		// Fall through to gopls
	case NodeKindFunction, NodeKindComponent, NodeKindGoDecl:
		// Try local AST-based lookup first (avoids gopls offset issues)
		if ctx.Document.AST != nil && word != "" {
			if loc := d.findGoDeclNameInAST(ctx.Document.AST, word, ctx.Document.URI); loc != nil {
				return []Location{*loc}, nil
			}
		}
		locs, err := d.getGoplsDefinition(ctx)
		if err == nil && len(locs) > 0 {
			return locs, nil
		}
	}

	// Gopls fallback for Go expressions not resolved by handlers above.
	if ctx.InGoExpr {
		locs, err := d.getGoplsDefinition(ctx)
		if err != nil {
			log.Server("gopls definition error: %v", err)
		} else if len(locs) > 0 {
			return locs, nil
		}
	}

	// Word-based fallbacks
	componentName := strings.TrimPrefix(word, "@")

	// Look up component in index
	if info, ok := d.index.Lookup(componentName); ok {
		return []Location{info.Location}, nil
	}

	// Check if it's a function (use componentName with @ stripped)
	if funcInfo, ok := d.index.LookupFunc(componentName); ok {
		return []Location{funcInfo.Location}, nil
	}

	// Check within component scope
	if ctx.Scope.Component != nil {
		compName := ctx.Scope.Component.Name

		// Parameter
		if paramInfo, ok := d.index.LookupParam(compName, word); ok {
			return []Location{paramInfo.Location}, nil
		}

		// Let binding
		if loc := d.findLetBindingDefinition(ctx, word); loc != nil {
			return []Location{*loc}, nil
		}

		// For loop variable
		if loc := d.findLoopVariableDefinition(ctx, word); loc != nil {
			return []Location{*loc}, nil
		}

		// GoCode variable
		if loc := d.findGoCodeVariableDefinition(ctx, word); loc != nil {
			return []Location{*loc}, nil
		}
	}

	// AST-based component/function/type definition within current file
	if ctx.Document.AST != nil {
		if loc := d.findComponentInAST(ctx.Document.AST, componentName, ctx.Document.URI); loc != nil {
			return []Location{*loc}, nil
		}
		if loc := d.findFuncInAST(ctx.Document.AST, word, ctx.Document.URI); loc != nil {
			return []Location{*loc}, nil
		}
		if loc := d.findGoDeclNameInAST(ctx.Document.AST, word, ctx.Document.URI); loc != nil {
			return []Location{*loc}, nil
		}
	}

	return nil, nil
}

// --- Component and function definition ---

func (d *definitionProvider) definitionComponentCall(ctx *CursorContext) ([]Location, error) {
	call, ok := ctx.Node.(*tuigen.ComponentCall)
	if !ok || call == nil {
		return nil, nil
	}

	if info, ok := d.index.Lookup(call.Name); ok {
		return []Location{info.Location}, nil
	}

	// For struct-mount components (e.g., @Sidebar()), the component call name
	// refers to the constructor function, not a templ component name.
	if funcInfo, ok := d.index.LookupFunc(call.Name); ok {
		return []Location{funcInfo.Location}, nil
	}

	return nil, nil
}

// definitionRefFromScope checks if the word under the cursor matches a
// ref variable in the component scope and returns its ref={} definition position.
func (d *definitionProvider) definitionRefFromScope(ctx *CursorContext) []Location {
	if ctx.Scope.Component == nil {
		return nil
	}
	for _, ref := range ctx.Scope.Refs {
		if ref.Name == ctx.Word && ref.Element != nil {
			lineIdx, charIdx, found := findRefAttrPosition(ctx.Document.Content, ref.Element)
			if found {
				refAttr := "ref={" + ref.Name + "}"
				return []Location{{
					URI: ctx.Document.URI,
					Range: Range{
						Start: Position{Line: lineIdx, Character: charIdx},
						End:   Position{Line: lineIdx, Character: charIdx + len(refAttr)},
					},
				}}
			}
		}
	}
	return nil
}

func (d *definitionProvider) definitionRefAttr(ctx *CursorContext) ([]Location, error) {
	elem, ok := ctx.Node.(*tuigen.Element)
	if !ok || elem == nil || elem.RefExpr == nil {
		return nil, nil
	}

	refName := elem.RefExpr.Code

	// Try to find the variable declaration (e.g., content := tui.NewRef())
	if ctx.Scope.Component != nil && ctx.Document.AST != nil {
		if loc := d.findGoCodeVariableDefinition(ctx, refName); loc != nil {
			return []Location{*loc}, nil
		}

		// For dotted names (e.g., c.textareaRef), search struct field definitions
		if strings.Contains(refName, ".") {
			parts := strings.SplitN(refName, ".", 2)
			if len(parts) == 2 {
				fieldName := parts[1]
				if loc := d.findGoDeclNameInAST(ctx.Document.AST, fieldName, ctx.Document.URI); loc != nil {
					return []Location{*loc}, nil
				}
			}
		}
	}

	// Fall back to pointing to the ref={} attribute itself
	lineIdx, charIdx, found := findRefAttrPosition(ctx.Document.Content, elem)
	if !found {
		// Fallback to element tag position
		lineIdx = elem.Position.Line - 1
		charIdx = elem.Position.Column - 1
	}

	refAttr := "ref={" + refName + "}"
	return []Location{{
		URI: ctx.Document.URI,
		Range: Range{
			Start: Position{Line: lineIdx, Character: charIdx},
			End:   Position{Line: lineIdx, Character: charIdx + len(refAttr)},
		},
	}}, nil
}

// findRefAttrPosition finds the source position of ref={name} for an element.
// Searches from the element's tag line through subsequent lines to handle
// multiline elements where ref={} is on its own line.
// Returns 0-indexed line and column.
func findRefAttrPosition(content string, elem *tuigen.Element) (line, col int, found bool) {
	if elem == nil || elem.RefExpr == nil {
		return 0, 0, false
	}

	refAttr := "ref={" + elem.RefExpr.Code + "}"
	lines := strings.Split(content, "\n")
	startLine := elem.Position.Line - 1 // 0-indexed

	maxSearch := min(startLine+20, len(lines))

	for lineIdx := startLine; lineIdx < maxSearch; lineIdx++ {
		idx := strings.Index(lines[lineIdx], refAttr)
		if idx >= 0 {
			return lineIdx, idx, true
		}
	}

	return 0, 0, false
}

func (d *definitionProvider) definitionStateVar(ctx *CursorContext) ([]Location, error) {
	// Find the state variable declaration in scope, matching by name
	for _, sv := range ctx.Scope.StateVars {
		if sv.Name == ctx.Word {
			return []Location{{
				URI: ctx.Document.URI,
				Range: Range{
					Start: Position{Line: sv.Position.Line - 1, Character: sv.Position.Column - 1},
					End:   Position{Line: sv.Position.Line - 1, Character: sv.Position.Column - 1 + len(sv.Name)},
				},
			}}, nil
		}
	}
	return nil, nil
}

func (d *definitionProvider) definitionEventHandler(ctx *CursorContext) ([]Location, error) {
	// Event handler attributes — try to find the handler function in Go expressions
	// For now, fall back to gopls for Go expression resolution
	if ctx.InGoExpr {
		return d.getGoplsDefinition(ctx)
	}
	return nil, nil
}

func (d *definitionProvider) definitionParameter(ctx *CursorContext) ([]Location, error) {
	word := ctx.Word

	// Function parameter
	if ctx.Scope.Function != nil {
		funcName := parseFuncName(ctx.Scope.Function.Code)
		if paramInfo, ok := d.index.LookupFuncParam(funcName, word); ok {
			return []Location{paramInfo.Location}, nil
		}
	}

	// Component parameter
	if ctx.Scope.Component != nil {
		if paramInfo, ok := d.index.LookupParam(ctx.Scope.Component.Name, word); ok {
			return []Location{paramInfo.Location}, nil
		}
	}

	return nil, nil
}

// --- Local variable definitions ---

func (d *definitionProvider) findLetBindingDefinition(ctx *CursorContext, varName string) *Location {
	if ctx.Document.AST == nil || ctx.Scope.Component == nil {
		return nil
	}

	for _, comp := range ctx.Document.AST.Components {
		if comp.Name != ctx.Scope.Component.Name {
			continue
		}

		if binding := findLetBindingInNodes(comp.Body, varName); binding != nil {
			nameOffset := letBindingNameOffset(binding)
			return &Location{
				URI: ctx.Document.URI,
				Range: Range{
					Start: Position{
						Line:      binding.Position.Line - 1,
						Character: binding.Position.Column - 1 + nameOffset,
					},
					End: Position{
						Line:      binding.Position.Line - 1,
						Character: binding.Position.Column - 1 + nameOffset + len(varName),
					},
				},
			}
		}
	}
	return nil
}

func (d *definitionProvider) findLoopVariableDefinition(ctx *CursorContext, varName string) *Location {
	if ctx.Document.AST == nil || ctx.Scope.Component == nil {
		return nil
	}

	for _, comp := range ctx.Document.AST.Components {
		if comp.Name != ctx.Scope.Component.Name {
			continue
		}

		loop := findForLoopWithVariable(comp.Body, varName)
		if loop == nil {
			return nil
		}

		if loop.Index == varName {
			return &Location{
				URI: ctx.Document.URI,
				Range: Range{
					Start: Position{
						Line:      loop.Position.Line - 1,
						Character: loop.Position.Column - 1 + len("for "),
					},
					End: Position{
						Line:      loop.Position.Line - 1,
						Character: loop.Position.Column - 1 + len("for ") + len(varName),
					},
				},
			}
		} else if loop.Value == varName {
			offset := len("for ")
			if loop.Index != "" {
				offset += len(loop.Index) + 2 // ", "
			}
			return &Location{
				URI: ctx.Document.URI,
				Range: Range{
					Start: Position{
						Line:      loop.Position.Line - 1,
						Character: loop.Position.Column - 1 + offset,
					},
					End: Position{
						Line:      loop.Position.Line - 1,
						Character: loop.Position.Column - 1 + offset + len(varName),
					},
				},
			}
		}
	}
	return nil
}

func (d *definitionProvider) findGoCodeVariableDefinition(ctx *CursorContext, varName string) *Location {
	if ctx.Document.AST == nil || ctx.Scope.Component == nil {
		return nil
	}

	for _, comp := range ctx.Document.AST.Components {
		if comp.Name != ctx.Scope.Component.Name {
			continue
		}

		goCode := findGoCodeWithVariable(comp.Body, varName)
		if goCode == nil {
			return nil
		}

		idx := findVarDeclPosition(goCode.Code, varName)
		if idx >= 0 {
			return &Location{
				URI: ctx.Document.URI,
				Range: Range{
					Start: Position{
						Line:      goCode.Position.Line - 1,
						Character: goCode.Position.Column - 1 + idx,
					},
					End: Position{
						Line:      goCode.Position.Line - 1,
						Character: goCode.Position.Column - 1 + idx + len(varName),
					},
				},
			}
		}
	}
	return nil
}

// --- AST lookup helpers ---

func (d *definitionProvider) findComponentInAST(ast *tuigen.File, name string, uri string) *Location {
	for _, comp := range ast.Components {
		if comp.Name == name {
			return &Location{
				URI: uri,
				Range: Range{
					Start: Position{Line: comp.Position.Line - 1, Character: comp.Position.Column - 1},
					End:   Position{Line: comp.Position.Line - 1, Character: comp.Position.Column - 1 + len("templ") + 1 + len(comp.Name)},
				},
			}
		}
	}
	return nil
}

func (d *definitionProvider) findFuncInAST(ast *tuigen.File, name string, uri string) *Location {
	for _, fn := range ast.Funcs {
		fnName := parseFuncName(fn.Code)
		if fnName == name {
			// Find the actual offset of the name in the code. For methods
			// like "func (c *chat) updateHeight()", the name doesn't
			// immediately follow "func ".
			nameIdx := max(strings.Index(fn.Code, fnName+"("), 0)
			startCol := fn.Position.Column - 1 + nameIdx
			return &Location{
				URI: uri,
				Range: Range{
					Start: Position{Line: fn.Position.Line - 1, Character: startCol},
					End:   Position{Line: fn.Position.Line - 1, Character: startCol + len(fnName)},
				},
			}
		}
	}
	return nil
}

// findGoDeclNameInAST searches GoDecl nodes for a type, var, or const name.
// Works for type declarations (type Foo struct{...}), var declarations, etc.
func (d *definitionProvider) findGoDeclNameInAST(ast *tuigen.File, name string, uri string) *Location {
	for _, decl := range ast.Decls {
		code := decl.Code
		// The Code includes the keyword (type/var/const). Extract the declared name.
		// For "type chat struct {" the name is "chat".
		// For "var _ tui.AppBinder = ..." the name is "_".
		trimmed := strings.TrimSpace(code)
		// Remove the keyword prefix
		rest := ""
		if strings.HasPrefix(trimmed, decl.Kind+" ") {
			rest = strings.TrimSpace(trimmed[len(decl.Kind)+1:])
		} else if strings.HasPrefix(trimmed, decl.Kind+"\t") {
			rest = strings.TrimSpace(trimmed[len(decl.Kind)+1:])
		}
		if rest == "" {
			continue
		}

		// Extract the first word (the declared name)
		declName := ""
		for i, ch := range rest {
			if ch == ' ' || ch == '\t' || ch == '(' || ch == '=' {
				declName = rest[:i]
				break
			}
		}
		if declName == "" {
			// Single word (e.g., "const Foo")
			declName = rest
		}

		if declName == name {
			// Find the column of the name in the source
			nameIdx := strings.Index(code, name)
			col := decl.Position.Column - 1
			if nameIdx >= 0 {
				col += nameIdx
			}
			return &Location{
				URI: uri,
				Range: Range{
					Start: Position{Line: decl.Position.Line - 1, Character: col},
					End:   Position{Line: decl.Position.Line - 1, Character: col + len(name)},
				},
			}
		}

		// Also check for struct field definitions within the declaration.
		// For "type chat struct { ... showSettings *tui.State[bool] ... }",
		// search the struct body for field names.
		if strings.Contains(code, "struct {") || strings.Contains(code, "struct{") {
			lines := strings.Split(code, "\n")
			for lineIdx, line := range lines {
				trimmedLine := strings.TrimSpace(line)
				// Skip struct opening/closing and empty lines
				if trimmedLine == "" || trimmedLine == "{" || trimmedLine == "}" ||
					strings.HasPrefix(trimmedLine, "type ") || strings.HasPrefix(trimmedLine, "//") {
					continue
				}
				// First word on the line is the field name
				fields := strings.Fields(trimmedLine)
				if len(fields) >= 2 && fields[0] == name {
					fieldIdx := strings.Index(line, name)
					fieldCol := 0
					if lineIdx == 0 {
						fieldCol = decl.Position.Column - 1
					}
					if fieldIdx >= 0 {
						fieldCol += fieldIdx
					}
					return &Location{
						URI: uri,
						Range: Range{
							Start: Position{Line: decl.Position.Line - 1 + lineIdx, Character: fieldCol},
							End:   Position{Line: decl.Position.Line - 1 + lineIdx, Character: fieldCol + len(name)},
						},
					}
				}
			}
		}
	}
	return nil
}

// --- gopls definition delegation ---

func (d *definitionProvider) getGoplsDefinition(ctx *CursorContext) ([]Location, error) {
	proxy := d.goplsProxy.GetProxy()
	if proxy == nil {
		return nil, nil
	}

	cached := d.virtualFiles.GetVirtualFile(ctx.Document.URI)
	if cached == nil || cached.SourceMap == nil {
		return nil, nil
	}

	goLine, goCol, found := cached.SourceMap.TuiToGo(ctx.Position.Line, ctx.Position.Character)
	if !found {
		return nil, nil
	}

	goplsLocs, err := proxy.Definition(cached.GoURI, gopls.Position{
		Line:      goLine,
		Character: goCol,
	})
	if err != nil {
		return nil, err
	}

	if len(goplsLocs) == 0 {
		return nil, nil
	}

	var locs []Location
	for _, gl := range goplsLocs {
		// Check if this is a virtual file — translate back to .gsx
		if gopls.IsVirtualGoFile(gl.URI) {
			tuiURI := gopls.GoURIToTuiURI(gl.URI)
			cachedFile := d.virtualFiles.GetVirtualFile(tuiURI)
			if cachedFile != nil && cachedFile.SourceMap != nil {
				tuiStartLine, tuiStartCol, startFound := cachedFile.SourceMap.GoToTui(gl.Range.Start.Line, gl.Range.Start.Character)
				tuiEndLine, tuiEndCol, endFound := cachedFile.SourceMap.GoToTui(gl.Range.End.Line, gl.Range.End.Character)
				if startFound && endFound {
					locs = append(locs, Location{
						URI: tuiURI,
						Range: Range{
							Start: Position{Line: tuiStartLine, Character: tuiStartCol},
							End:   Position{Line: tuiEndLine, Character: tuiEndCol},
						},
					})
					continue
				}
			}
			// Translation failed for virtual file — skip instead of returning
			// a nonexistent virtual URI. The caller's word-based fallback will
			// try AST-based lookup.
			log.Server("gopls returned virtual file %s but source map translation failed, skipping", gl.URI)
			continue
		}

		// Real generated _gsx.go files have structural differences from
		// the virtual Go file (different ordering, goimports blank lines),
		// making source map reverse-translation unreliable. Skip these
		// and let the word-based fallback handle them via AST lookup.
		if gopls.IsGeneratedGoFile(gl.URI) {
			log.Server("gopls returned generated file %s, skipping (word-based fallback preferred)", gl.URI)
			continue
		}

		// External file (standard library, etc.) — return as-is
		locs = append(locs, Location{
			URI: gl.URI,
			Range: Range{
				Start: Position{Line: gl.Range.Start.Line, Character: gl.Range.Start.Character},
				End:   Position{Line: gl.Range.End.Line, Character: gl.Range.End.Character},
			},
		})
	}

	return locs, nil
}

// --- Import definition ---

// definitionImport resolves go-to-definition for an import path by finding the
// quoted path in the virtual .go file and asking gopls to resolve it.
func (d *definitionProvider) definitionImport(ctx *CursorContext) ([]Location, error) {
	importPath := ctx.ImportPath
	if importPath == "" {
		return nil, nil
	}

	proxy := d.goplsProxy.GetProxy()
	if proxy == nil {
		log.Server("definitionImport: no gopls proxy available")
		return nil, nil
	}

	cached := d.virtualFiles.GetVirtualFile(ctx.Document.URI)
	if cached == nil {
		log.Server("definitionImport: no virtual file for %s", ctx.Document.URI)
		return nil, nil
	}

	// Find the quoted import path in the virtual Go file content.
	quotedPath := `"` + importPath + `"`
	idx := strings.Index(cached.Content, quotedPath)
	if idx < 0 {
		log.Server("definitionImport: import path %q not found in virtual file", importPath)
		return nil, nil
	}

	// Convert byte offset to line/character and position inside the quotes.
	goLine, goCol := offsetToLineChar(cached.Content, idx+1) // +1 skips opening quote

	log.Server("definitionImport: asking gopls for %q at GoLine=%d GoCol=%d", importPath, goLine, goCol)

	goplsLocs, err := proxy.Definition(cached.GoURI, gopls.Position{
		Line:      goLine,
		Character: goCol,
	})
	if err != nil {
		log.Server("definitionImport: gopls error: %v", err)
		return nil, err
	}

	if len(goplsLocs) == 0 {
		return nil, nil
	}

	// Import definitions always resolve to external .go files, so no
	// source map reverse-translation is needed.
	var locs []Location
	for _, gl := range goplsLocs {
		locs = append(locs, Location{
			URI: gl.URI,
			Range: Range{
				Start: Position{Line: gl.Range.Start.Line, Character: gl.Range.Start.Character},
				End:   Position{Line: gl.Range.End.Line, Character: gl.Range.End.Character},
			},
		})
	}
	return locs, nil
}

// offsetToLineChar converts a byte offset in content to 0-indexed line and character.
func offsetToLineChar(content string, offset int) (int, int) {
	line := 0
	lineStart := 0
	for i := 0; i < offset && i < len(content); i++ {
		if content[i] == '\n' {
			line++
			lineStart = i + 1
		}
	}
	return line, offset - lineStart
}