-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathserver.go
More file actions
4898 lines (4407 loc) · 149 KB
/
Copy pathserver.go
File metadata and controls
4898 lines (4407 loc) · 149 KB
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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package lsp
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"log"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"go.lsp.dev/jsonrpc2"
"go.lsp.dev/protocol"
"go.lsp.dev/uri"
"go.uber.org/zap"
"github.com/remoteoss/dexter/internal/parser"
"github.com/remoteoss/dexter/internal/stdlib"
"github.com/remoteoss/dexter/internal/store"
"github.com/remoteoss/dexter/internal/treesitter"
"github.com/remoteoss/dexter/internal/version"
)
// optBinding represents a dynamic import/use in __using__ driven by opts.
// For example: `mod = Keyword.get(opts, :mod, Mox)` followed by `import unquote(mod)`
// produces: {optKey: "mod", defaultMod: "Mox", kind: "import"}.
type optBinding struct {
optKey string // keyword key in opts (e.g. "mod")
defaultMod string // default module if opt not provided (e.g. "Mox"); empty if none
kind string // "import" or "use"
}
// usingCacheEntry holds the full parsed result of a module's defmacro __using__
// body, keyed by module name. Storing filePath avoids a LookupModule query on
// cache hits; mtime invalidates the entry when the source file changes.
type usingCacheEntry struct {
mtime int64
filePath string
imports []string // modules imported in __using__, source order
inlineDefs map[string][]inlineDef // function name → inline defs in quote do block
transUses []string // modules used inside __using__ body (double-use chains)
optBindings []optBinding // dynamic imports/uses resolved from opts
aliases map[string]string // alias short name → full module injected by __using__
}
type Server struct {
store *store.Store
docs *DocumentStore
projectRoot string
explicitRoot bool // true when projectRoot was provided via CLI, not inferred from Initialize
stdlibRoot string
initialized bool
client protocol.Client
followDelegates bool
debug bool
definitionStyle string // "all" (default) or "first": controls multi-head definition results
mixBin string // resolved path to the mix binary
formatters map[string]*formatterProcess // formatterExs path → persistent formatter
formattersMu sync.Mutex
usingCache map[string]*usingCacheEntry // module name → parsed __using__ result
usingCacheMu sync.RWMutex
depsCache map[string]bool // dir → whether files in that dir are deps
depsCacheMu sync.RWMutex
conn jsonrpc2.Conn // raw connection for server-initiated requests not on the Client interface
showDocumentSupported bool // client supports window/showDocument (LSP 3.16+)
snippetSupport bool // client supports snippet insert text in completions
reindexing sync.Mutex // serializes concurrent backgroundReindex calls
notifiedOTPMismatch sync.Once // prevents repeated OTP mismatch warnings
backgroundWork sync.WaitGroup // tracks background reindex goroutines so the store isn't closed while they're running
}
func (s *Server) debugf(format string, args ...interface{}) {
if s.debug {
log.Printf("[debug] "+format, args...)
}
}
func (s *Server) debugNow() time.Time {
if s.debug {
return time.Now()
}
return time.Time{}
}
func NewServer(s *store.Store, projectRoot string) *Server {
return &Server{
store: s,
docs: NewDocumentStore(),
projectRoot: projectRoot,
explicitRoot: projectRoot != "",
followDelegates: true,
definitionStyle: "all",
usingCache: make(map[string]*usingCacheEntry),
depsCache: make(map[string]bool),
}
}
type stdinoutCloser struct {
io.Reader
io.Writer
}
func (s stdinoutCloser) Close() error { return nil }
// Serve starts the LSP server on the given reader/writer (typically stdin/stdout).
func Serve(in io.Reader, out io.Writer, s *store.Store, projectRoot string) error {
server := NewServer(s, projectRoot)
logger, _ := zap.NewProduction()
stream := jsonrpc2.NewStream(stdinoutCloser{in, out})
conn := jsonrpc2.NewConn(stream)
server.client = protocol.ClientDispatcher(conn, logger)
server.conn = conn
handler := protocol.ServerHandler(server, nil)
ctx := context.Background()
conn.Go(ctx, handler)
<-conn.Done()
return conn.Err()
}
// backgroundReindex runs in the background. If the index is empty it does a
// full init, otherwise it does an incremental mtime-based update.
func (s *Server) backgroundReindex() {
s.backgroundWork.Add(1)
go func() {
defer s.backgroundWork.Done()
if !s.reindexing.TryLock() {
return
}
defer s.reindexing.Unlock()
start := time.Now()
reindexed := 0
isEmpty := s.store.IsEmpty()
if isEmpty {
log.Printf("No index found, building from scratch...")
if s.client != nil {
if err := s.client.ShowMessage(context.Background(), &protocol.ShowMessageParams{
Type: protocol.MessageTypeInfo,
Message: "Dexter: building index for the first time, go-to-definition will be available shortly...",
}); err != nil {
log.Printf("ShowMessage: %v", err)
}
}
}
seen := make(map[string]struct{})
walkAndIndex := func(root string, indexRefs bool) {
_ = parser.WalkElixirFiles(root, func(path string, d fs.DirEntry) error {
seen[path] = struct{}{}
if !isEmpty {
info, err := d.Info()
if err != nil {
return nil
}
storedMtime, found := s.store.GetFileMtime(path)
currentMtime := info.ModTime().UnixNano()
if found && storedMtime == currentMtime {
return nil
}
}
defs, refs, err := parser.ParseFile(path)
if err != nil {
return nil
}
if !indexRefs {
refs = nil
}
if err := s.store.IndexFileWithRefs(path, defs, refs); err != nil {
log.Printf("Warning: reindex %s: %v", path, err)
}
reindexed++
return nil
})
}
// Index stdlib first (definitions only).
if s.stdlibRoot != "" {
walkAndIndex(s.stdlibRoot, false)
}
walkAndIndex(s.projectRoot, true)
// Prune store entries for files no longer on disk
if storedPaths, err := s.store.ListFilePaths(); err == nil {
var toRemove []string
for _, storedPath := range storedPaths {
if _, ok := seen[storedPath]; !ok {
toRemove = append(toRemove, storedPath)
}
}
if len(toRemove) > 0 {
_ = s.store.RemoveFiles(toRemove)
}
}
elapsed := time.Since(start).Round(time.Millisecond)
log.Printf("Background reindex: %d files updated (%s)", reindexed, elapsed)
if isEmpty && s.client != nil {
if err := s.client.ShowMessage(context.Background(), &protocol.ShowMessageParams{
Type: protocol.MessageTypeInfo,
Message: fmt.Sprintf("Dexter: index built (%d files in %s)", reindexed, elapsed),
}); err != nil {
log.Printf("ShowMessage: %v", err)
}
}
}()
}
// watchGitHead polls .git/HEAD mtime and triggers reindex on branch switches.
func (s *Server) watchGitHead() {
go func() {
headPath := filepath.Join(s.projectRoot, ".git", "HEAD")
var lastMtime int64
info, err := os.Stat(headPath)
if err != nil {
return // no .git, skip
}
lastMtime = info.ModTime().UnixNano()
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for range ticker.C {
info, err := os.Stat(headPath)
if err != nil {
continue
}
currentMtime := info.ModTime().UnixNano()
if currentMtime != lastMtime {
lastMtime = currentMtime
log.Printf("Git HEAD changed, reindexing...")
s.backgroundReindex()
}
}
}()
}
// notifyOTPMismatch checks stderr output for an OTP version mismatch and
// sends a one-time warning to the editor so the user doesn't have to dig
// through logs.
func (s *Server) notifyOTPMismatch(stderr string) {
if s.client == nil || !strings.Contains(stderr, "requires a more recent Erlang/OTP") {
return
}
s.notifiedOTPMismatch.Do(func() {
_ = s.client.ShowMessage(context.Background(), &protocol.ShowMessageParams{
Type: protocol.MessageTypeError,
Message: "Dexter: Elixir/OTP version mismatch - your Elixir install for this project was compiled for a newer OTP version than what is running. Update your Erlang to match, or switch to an Elixir build that targets your current OTP (e.g. elixir@...-otp-27).",
})
})
}
// === LSP Lifecycle ===
func (s *Server) Initialize(ctx context.Context, params *protocol.InitializeParams) (*protocol.InitializeResult, error) {
if !s.explicitRoot {
if len(params.WorkspaceFolders) > 0 {
root := uriToPath(protocol.DocumentURI(params.WorkspaceFolders[0].URI))
if root != "" {
s.projectRoot = findDexterRoot(root)
}
} else if params.RootURI != "" { //nolint:staticcheck // RootURI is deprecated but Neovim still sends it
root := uriToPath(params.RootURI) //nolint:staticcheck
if root != "" {
s.projectRoot = findDexterRoot(root)
}
}
}
var explicitStdlibPath string
if opts, ok := params.InitializationOptions.(map[string]interface{}); ok {
if v, ok := opts["followDelegates"].(bool); ok {
s.followDelegates = v
}
if v, ok := opts["stdlibPath"].(string); ok {
explicitStdlibPath = v
}
if v, ok := opts["debug"].(bool); ok {
s.debug = v
}
if v, ok := opts["definitionStyle"].(string); ok {
if v == "all" || v == "first" {
s.definitionStyle = v
}
}
}
if os.Getenv("DEXTER_DEBUG") == "true" {
s.debug = true
}
log.Printf("Initialize: projectRoot=%s debug=%v", s.projectRoot, s.debug)
if root, ok := stdlib.Resolve(s.store, explicitStdlibPath, s.projectRoot); ok {
s.stdlibRoot = root
log.Printf("Elixir stdlib at: %s", root)
// Derive mix binary from the same Elixir install
mixBin := filepath.Join(root, "..", "bin", "mix")
if resolved, err := filepath.Abs(mixBin); err == nil {
mixBin = resolved
}
if _, err := os.Stat(mixBin); err == nil {
s.mixBin = mixBin
log.Printf("Mix binary at: %s", mixBin)
}
} else {
log.Printf("Could not detect Elixir stdlib (set stdlibPath in initializationOptions or DEXTER_ELIXIR_LIB_ROOT)")
if s.client != nil {
_ = s.client.ShowMessage(context.Background(), &protocol.ShowMessageParams{
Type: protocol.MessageTypeWarning,
Message: "Dexter: could not detect Elixir stdlib - stdlib modules (Enum, String, etc.) won't resolve. Verify the Elixir version in your .tool-versions or mise.toml is installed (e.g. `mise install`), or set DEXTER_ELIXIR_LIB_ROOT.",
})
}
}
// Fallback: find mix in PATH
if s.mixBin == "" {
if p, err := exec.LookPath("mix"); err == nil {
s.mixBin = p
log.Printf("Mix binary at: %s (PATH fallback)", p)
} else {
log.Printf("Could not find mix binary — formatting will not work")
}
}
if !s.initialized {
s.initialized = true
s.backgroundReindex()
s.watchGitHead()
}
if params.Capabilities.Window != nil && params.Capabilities.Window.ShowDocument != nil {
s.showDocumentSupported = params.Capabilities.Window.ShowDocument.Support
}
if params.Capabilities.TextDocument != nil && params.Capabilities.TextDocument.Completion != nil &&
params.Capabilities.TextDocument.Completion.CompletionItem != nil {
s.snippetSupport = params.Capabilities.TextDocument.Completion.CompletionItem.SnippetSupport
}
result := &protocol.InitializeResult{
Capabilities: protocol.ServerCapabilities{
TextDocumentSync: protocol.TextDocumentSyncOptions{
OpenClose: true,
Change: protocol.TextDocumentSyncKindFull,
WillSaveWaitUntil: false,
Save: &protocol.SaveOptions{
IncludeText: false,
},
},
DefinitionProvider: true,
TypeDefinitionProvider: true,
DeclarationProvider: true,
ImplementationProvider: true,
ReferencesProvider: true,
DocumentFormattingProvider: true,
HoverProvider: true,
DocumentHighlightProvider: true,
DocumentSymbolProvider: true,
WorkspaceSymbolProvider: true,
FoldingRangeProvider: true,
CodeActionProvider: true,
RenameProvider: &protocol.RenameOptions{PrepareProvider: true},
CallHierarchyProvider: true,
CompletionProvider: &protocol.CompletionOptions{
TriggerCharacters: []string{"."},
ResolveProvider: true,
},
SignatureHelpProvider: &protocol.SignatureHelpOptions{
TriggerCharacters: []string{"(", ","},
RetriggerCharacters: []string{")"},
},
},
ServerInfo: &protocol.ServerInfo{
Name: "dexter",
Version: version.Version,
},
}
s.debugf("Initialize: capabilities: %+v", result.Capabilities)
return result, nil
}
func (s *Server) Initialized(ctx context.Context, params *protocol.InitializedParams) error {
if s.client != nil {
go func() {
if err := s.client.RegisterCapability(context.Background(), &protocol.RegistrationParams{
Registrations: []protocol.Registration{
{
ID: "dexter-file-watcher",
Method: "workspace/didChangeWatchedFiles",
RegisterOptions: protocol.DidChangeWatchedFilesRegistrationOptions{
Watchers: []protocol.FileSystemWatcher{
{GlobPattern: "**/*.ex", Kind: protocol.WatchKindCreate + protocol.WatchKindChange + protocol.WatchKindDelete},
{GlobPattern: "**/*.exs", Kind: protocol.WatchKindCreate + protocol.WatchKindChange + protocol.WatchKindDelete},
},
},
},
},
}); err != nil {
log.Printf("RegisterCapability: %v", err)
}
}()
}
return nil
}
func (s *Server) Shutdown(ctx context.Context) error {
s.closeFormatters()
return nil
}
func (s *Server) Exit(ctx context.Context) error {
os.Exit(0)
return nil
}
// === Document Sync ===
func (s *Server) DidOpen(ctx context.Context, params *protocol.DidOpenTextDocumentParams) error {
s.docs.Set(string(params.TextDocument.URI), params.TextDocument.Text)
// Eagerly start the persistent formatter so the first format is instant.
// Skip deps and stdlib files — we don't format those.
path := uriToPath(params.TextDocument.URI)
if path != "" && isFormattableFile(path) && s.isProjectFile(path) && !s.isDepsFile(path) {
go func() {
if mixRoot := findMixRoot(filepath.Dir(path)); mixRoot != "" {
formatterExs := findFormatterConfig(path, mixRoot)
_, _ = s.getFormatter(mixRoot, formatterExs)
}
}()
}
return nil
}
func (s *Server) DidChange(ctx context.Context, params *protocol.DidChangeTextDocumentParams) error {
if len(params.ContentChanges) > 0 {
// Full sync mode — last change contains the full text
s.docs.Set(string(params.TextDocument.URI), params.ContentChanges[len(params.ContentChanges)-1].Text)
}
return nil
}
func (s *Server) DidClose(ctx context.Context, params *protocol.DidCloseTextDocumentParams) error {
s.docs.Close(string(params.TextDocument.URI))
return nil
}
func (s *Server) DidSave(ctx context.Context, params *protocol.DidSaveTextDocumentParams) error {
path := uriToPath(params.TextDocument.URI)
if path == "" || !parser.IsElixirFile(path) {
return nil
}
go func() {
defs, refs, err := parser.ParseFile(path)
if err != nil {
log.Printf("Error parsing %s: %v", path, err)
return
}
if err := s.store.IndexFileWithRefs(path, defs, refs); err != nil {
log.Printf("Error indexing %s: %v", path, err)
}
}()
return nil
}
func (s *Server) isProjectFile(path string) bool {
cleaned := filepath.Clean(path)
return strings.HasPrefix(cleaned, s.projectRoot+string(os.PathSeparator))
}
func isFormattableFile(path string) bool {
ext := filepath.Ext(path)
return ext == ".ex" || ext == ".exs" || ext == ".heex"
}
func (s *Server) mixCommand(ctx context.Context, dir string, args ...string) *exec.Cmd {
bin := s.mixBin
if bin == "" {
bin = "mix"
}
cmd := exec.CommandContext(ctx, bin, args...)
cmd.Dir = dir
return cmd
}
// === Definition ===
func (s *Server) Definition(ctx context.Context, params *protocol.DefinitionParams) ([]protocol.Location, error) {
docURI := string(params.TextDocument.URI)
if s.debug {
t0 := time.Now()
s.debugf("Definition request: uri=%s line=%d col=%d", docURI, params.Position.Line, params.Position.Character)
defer func() { s.debugf("Definition: total %s", time.Since(t0).Round(time.Microsecond)) }()
}
text, ok := s.docs.Get(docURI)
if !ok {
return nil, nil
}
lines := strings.Split(text, "\n")
lineNum := int(params.Position.Line)
col := int(params.Position.Character)
if lineNum >= len(lines) {
return nil, nil
}
// Get cached tokens for efficient multi-query operations
tf := s.docs.GetTokenizedFile(docURI)
if tf == nil {
tf = NewTokenizedFile(text)
}
// Check for @module_attribute reference first
if attrName := tf.ModuleAttributeAtCursor(lineNum, col); attrName != "" {
if line, found := FindModuleAttributeDefinition(text, attrName); found {
return []protocol.Location{{
URI: params.TextDocument.URI,
Range: lineRange(line - 1),
}}, nil
}
return nil, nil
}
exprCtx := tf.ExpressionAtCursor(lineNum, col)
if exprCtx.Empty() {
return nil, nil
}
expr := tf.ResolveModuleExpr(exprCtx.Expr(), lineNum)
moduleRef, functionName := ExtractModuleAndFunction(expr)
callArity := tf.ArityAtCallsite(lineNum, exprCtx.ExprStart, exprCtx.ExprEnd)
if moduleRef != "" {
if aliasParent, inBlock := ExtractAliasBlockParent(lines, lineNum); inBlock {
moduleRef = aliasParent + "." + moduleRef
}
}
aliases := tf.ExtractAliasesInScope(lineNum)
s.mergeAliasesFromUse(text, aliases)
s.debugf("Definition: expr=%q module=%q function=%q arity=%d", expr, moduleRef, functionName, callArity)
// Bare identifier — check variable first (cheap tree-sitter lookup), then functions
if moduleRef == "" {
if functionName == "" {
return nil, nil
}
// Variable go-to-definition via tree-sitter.
// The first occurrence in scope is the definition (pattern/assignment).
if tree, src, ok := s.docs.GetTree(docURI); ok {
if occs := treesitter.FindVariableOccurrencesWithTree(tree.RootNode(), src, uint(lineNum), uint(col)); len(occs) > 0 {
s.debugf("Definition: returning variable definition at line %d", occs[0].Line)
return []protocol.Location{{
URI: params.TextDocument.URI,
Range: lineRange(int(occs[0].Line)),
}}, nil
}
}
currentModule := tf.FirstDefmodule()
fullModule := s.resolveBareFunctionModule(uriToPath(protocol.DocumentURI(docURI)), text, lines, lineNum, functionName, aliases)
s.debugf("Definition: resolved bare %q -> %q", functionName, fullModule)
if fullModule == "" {
s.debugf("Definition: could not resolve bare function %q", functionName)
return nil, nil
}
// Current module — return buffer location directly (works before indexing)
if fullModule == currentModule {
if line, found := tf.FindFunctionDefinition(functionName); found {
return []protocol.Location{{
URI: params.TextDocument.URI,
Range: lineRange(line - 1),
}}, nil
}
}
// Look up via store
var results []store.LookupResult
var err error
if s.followDelegates {
results, err = s.store.LookupFollowDelegateByArity(fullModule, functionName, callArity)
} else {
results, err = s.store.LookupFunctionByArity(fullModule, functionName, callArity)
}
if err == nil && len(results) > 0 {
s.debugf("Definition: found %d result(s) in store for %s.%s", len(results), fullModule, functionName)
return s.applyDefinitionStyle(storeResultsToLocations(filterOutTypes(results))), nil
}
// fullModule may not directly define the function — try its use chain
// (e.g. `import MyApp.Factory` where MyApp.Factory uses ExMachina).
if results := s.lookupThroughUseOf(fullModule, functionName); len(results) > 0 {
s.debugf("Definition: found %d result(s) via use chain of %s for %s", len(results), fullModule, functionName)
return s.applyDefinitionStyle(storeResultsToLocations(filterOutTypes(results))), nil
}
// Fallback for use-chain inline defs (not stored as module definitions)
if results := s.lookupThroughUse(text, functionName, aliases); len(results) > 0 {
s.debugf("Definition: found %d result(s) via current file use chain for %s", len(results), functionName)
return s.applyDefinitionStyle(storeResultsToLocations(filterOutTypes(results))), nil
}
s.debugf("Definition: no result found for bare function %q in module %q", functionName, fullModule)
return nil, nil
}
// Module.function call — resolve aliases (including implicit nested-module aliases)
fullModule := s.resolveModuleWithNesting(moduleRef, aliases, uriToPath(params.TextDocument.URI), lineNum)
s.debugf("Definition: qualified call resolved %q -> %q", moduleRef, fullModule)
if functionName != "" {
var results []store.LookupResult
var err error
if s.followDelegates {
results, err = s.store.LookupFollowDelegateByArity(fullModule, functionName, callArity)
} else {
results, err = s.store.LookupFunctionByArity(fullModule, functionName, callArity)
}
if err == nil && len(results) > 0 {
s.debugf("Definition: found %d result(s) in store for %s.%s", len(results), fullModule, functionName)
return s.applyDefinitionStyle(storeResultsToLocations(filterOutTypes(results))), nil
}
// Not directly defined — the function may have been injected by a
// `use` macro in fullModule's source (e.g. Oban.Worker injects `new`).
if results := s.lookupThroughUseOf(fullModule, functionName); len(results) > 0 {
s.debugf("Definition: found %d result(s) via use chain of %s for %s", len(results), fullModule, functionName)
return s.applyDefinitionStyle(storeResultsToLocations(results)), nil
}
s.debugf("Definition: no result for %s.%s", fullModule, functionName)
}
// Fall back to module (fullModule already resolved via nesting above)
results, err := s.store.LookupModule(fullModule)
if err != nil || len(results) == 0 {
return nil, nil
}
return s.applyDefinitionStyle(storeResultsToLocations(results)), nil
}
func (s *Server) applyDefinitionStyle(locations []protocol.Location) []protocol.Location {
if s.definitionStyle == "first" && len(locations) > 1 {
return locations[:1]
}
return locations
}
func storeResultsToLocations(results []store.LookupResult) []protocol.Location {
type locKey struct {
filePath string
line int
}
seen := make(map[locKey]struct{}, len(results))
var locations []protocol.Location
for _, r := range results {
k := locKey{r.FilePath, r.Line}
if _, ok := seen[k]; ok {
continue
}
seen[k] = struct{}{}
locations = append(locations, protocol.Location{
URI: uri.File(r.FilePath),
Range: lineRange(r.Line - 1), // LSP lines are 0-based
})
}
return locations
}
var typeKinds = map[string]bool{"type": true, "typep": true, "opaque": true}
func filterOutTypes(results []store.LookupResult) []store.LookupResult {
var nonTypes []store.LookupResult
for _, r := range results {
if !typeKinds[r.Kind] {
nonTypes = append(nonTypes, r)
}
}
if len(nonTypes) > 0 {
return nonTypes
}
return results
}
func lineRange(line int) protocol.Range {
return protocol.Range{
Start: protocol.Position{Line: uint32(line), Character: 0},
End: protocol.Position{Line: uint32(line), Character: 0},
}
}
// nthLine returns the n-th line (0-based) from text without splitting the
// entire string. The bool indicates whether the line was found.
func nthLine(text string, n int) (string, bool) {
start := 0
for i := 0; i < n; i++ {
idx := strings.IndexByte(text[start:], '\n')
if idx < 0 {
return "", false
}
start += idx + 1
}
end := strings.IndexByte(text[start:], '\n')
if end < 0 {
return text[start:], true
}
return text[start : start+end], true
}
// findDexterRoot walks up from the given path looking for .dexter.db first,
// then .git (monorepo root), falling back to the original path.
func findDexterRoot(path string) string {
for _, marker := range []string{".dexter.db", ".git"} {
dir := path
for {
if _, err := os.Stat(filepath.Join(dir, marker)); err == nil {
return dir
}
parent := filepath.Dir(dir)
if parent == dir {
break
}
dir = parent
}
}
return path
}
// findMixRoot walks up from dir looking for the nearest mix.exs.
func findMixRoot(dir string) string {
for {
if _, err := os.Stat(filepath.Join(dir, "mix.exs")); err == nil {
return dir
}
parent := filepath.Dir(dir)
if parent == dir {
return ""
}
dir = parent
}
}
func uriToPath(u protocol.DocumentURI) string {
parsed := uri.URI(u)
return parsed.Filename()
}
// === No-op implementations for unused Server interface methods ===
func (s *Server) WorkDoneProgressCancel(ctx context.Context, params *protocol.WorkDoneProgressCancelParams) error {
return nil
}
func (s *Server) LogTrace(ctx context.Context, params *protocol.LogTraceParams) error { return nil }
func (s *Server) SetTrace(ctx context.Context, params *protocol.SetTraceParams) error { return nil }
func (s *Server) CodeAction(ctx context.Context, params *protocol.CodeActionParams) ([]protocol.CodeAction, error) {
docURI := string(params.TextDocument.URI)
text, ok := s.docs.Get(docURI)
if !ok {
return nil, nil
}
lines := strings.Split(text, "\n")
lineNum := int(params.Range.Start.Line)
if lineNum >= len(lines) {
return nil, nil
}
// Find the full dotted expression at the cursor so that "DocuSign.Client.request"
// gives us the complete module reference, not just the segment under the cursor.
col := int(params.Range.Start.Character)
tf := s.docs.GetTokenizedFile(docURI)
if tf == nil {
tf = NewTokenizedFile(text)
}
exprCtx := tf.FullExpressionAtCursor(lineNum, col)
if exprCtx.Empty() {
return nil, nil
}
moduleRef := exprCtx.ModuleRef
if moduleRef == "" {
return nil, nil
}
aliases := tf.ExtractAliasesInScope(lineNum)
s.mergeAliasesFromUse(text, aliases)
// Check if the first segment is already aliased — if so, the reference
// already resolves and no code action is needed.
firstSegment := moduleRef
if dot := strings.IndexByte(moduleRef, '.'); dot >= 0 {
firstSegment = moduleRef[:dot]
}
if _, aliased := aliases[firstSegment]; aliased {
return nil, nil
}
insertLine, indent := findAliasInsertPoint(lines)
var actions []protocol.CodeAction
// Case 1: Fully qualified module in the store (e.g. "MyApp.RandomAPI.Client").
// Offer to alias it and replace the usage with the short form.
if strings.Contains(moduleRef, ".") {
if defResults, err := s.store.LookupModule(moduleRef); err == nil && len(defResults) > 0 {
lastSegment := moduleLastSegment(moduleRef)
aliasText := indent + "alias " + moduleRef + "\n"
exprStart := exprCtx.ExprStart
var edits []protocol.TextEdit
// Insert the alias line
edits = append(edits, protocol.TextEdit{
Range: protocol.Range{
Start: protocol.Position{Line: uint32(insertLine), Character: 0},
End: protocol.Position{Line: uint32(insertLine), Character: 0},
},
NewText: aliasText,
})
// Replace the qualified module reference with the short name
edits = append(edits, protocol.TextEdit{
Range: protocol.Range{
Start: protocol.Position{Line: uint32(lineNum), Character: uint32(exprStart)},
End: protocol.Position{Line: uint32(lineNum), Character: uint32(exprStart + len(moduleRef))},
},
NewText: lastSegment,
})
actions = append(actions, protocol.CodeAction{
Title: "Add alias " + moduleRef,
Kind: protocol.QuickFix,
Edit: &protocol.WorkspaceEdit{
Changes: map[protocol.DocumentURI][]protocol.TextEdit{
protocol.DocumentURI(docURI): edits,
},
},
})
}
}
// Case 2: Short or partially-qualified name not in the store
// (e.g. "Client" or "DocuSign.Client"). Search for matching modules.
if len(actions) == 0 {
results, err := s.store.SearchModulesBySuffix(moduleRef)
if err == nil {
for _, r := range results {
if r.Module == moduleRef {
continue
}
suffix := "." + moduleRef
if !strings.HasSuffix(r.Module, suffix) {
continue
}
aliasTarget := r.Module
if strings.Contains(moduleRef, ".") {
aliasTarget = strings.TrimSuffix(r.Module, moduleRef[len(firstSegment):])
}
aliasText := indent + "alias " + aliasTarget + "\n"
actions = append(actions, protocol.CodeAction{
Title: "Add alias " + aliasTarget,
Kind: protocol.QuickFix,
Edit: &protocol.WorkspaceEdit{
Changes: map[protocol.DocumentURI][]protocol.TextEdit{
protocol.DocumentURI(docURI): {
{
Range: protocol.Range{
Start: protocol.Position{Line: uint32(insertLine), Character: 0},
End: protocol.Position{Line: uint32(insertLine), Character: 0},
},
NewText: aliasText,
},
},
},
},
})
if len(actions) >= 5 {
break
}
}
}
}
return actions, nil
}
// findAliasInsertPoint returns the 0-based line number where a new alias should
// be inserted and the indentation prefix to use. Places it after the last
// existing alias/import/use block, matching their indentation.
func findAliasInsertPoint(lines []string) (insertLine int, indent string) {
lastDirective := -1
lastIndent := " " // default to two spaces
moduleLineFound := false
for i, line := range lines {
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(trimmed, "defmodule ") {
moduleLineFound = true
if lastDirective < 0 {
lastDirective = i
}
continue
}
if moduleLineFound {
if strings.HasPrefix(trimmed, "alias ") || strings.HasPrefix(trimmed, "import ") ||
strings.HasPrefix(trimmed, "use ") || strings.HasPrefix(trimmed, "require ") {
lastDirective = i
lastIndent = line[:len(line)-len(strings.TrimLeft(line, " \t"))]
}
}
}
if lastDirective >= 0 {
return lastDirective + 1, lastIndent
}
return 0, lastIndent
}
func (s *Server) CodeLens(ctx context.Context, params *protocol.CodeLensParams) ([]protocol.CodeLens, error) {
return nil, nil
}
func (s *Server) CodeLensResolve(ctx context.Context, params *protocol.CodeLens) (*protocol.CodeLens, error) {
return nil, nil
}
func (s *Server) ColorPresentation(ctx context.Context, params *protocol.ColorPresentationParams) ([]protocol.ColorPresentation, error) {
return nil, nil
}
func (s *Server) Completion(ctx context.Context, params *protocol.CompletionParams) (*protocol.CompletionList, error) {
docURI := string(params.TextDocument.URI)
text, ok := s.docs.Get(docURI)
if !ok {
return nil, nil
}
lines := strings.Split(text, "\n")
lineNum := int(params.Position.Line)
col := int(params.Position.Character)
if lineNum >= len(lines) {
return nil, nil
}
prefix, afterDot, prefixStartCol := ExtractCompletionContext(lines[lineNum], col)
// Inside a multi-line alias block: complete child module segments under the parent.
if aliasParent, inBlock := ExtractAliasBlockParent(lines, lineNum); inBlock {
searchParent := aliasParent
segmentPrefix := prefix
labelPrefix := ""
if afterDot && prefix != "" {
searchParent = aliasParent + "." + prefix
segmentPrefix = ""
labelPrefix = prefix + "."
} else if prefix != "" {
if dotIdx := strings.LastIndexByte(prefix, '.'); dotIdx >= 0 {
searchParent = aliasParent + "." + prefix[:dotIdx]
segmentPrefix = prefix[dotIdx+1:]
labelPrefix = prefix[:dotIdx+1]
}
}
segments, err := s.store.SearchSubmoduleSegments(searchParent, segmentPrefix)
if err != nil {
return nil, nil
}
var items []protocol.CompletionItem
for _, segment := range segments {
items = append(items, protocol.CompletionItem{
Label: labelPrefix + segment,
Kind: protocol.CompletionItemKindModule,
Detail: searchParent + "." + segment,
})