Repository navigation
Expand file tree
/
Copy pathls.nim
More file actions
1538 lines (1365 loc) · 53.3 KB
/
Copy pathls.nim
File metadata and controls
1538 lines (1365 loc) · 53.3 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
{.push raises: [], gcsafe.}
import
std/[
macros, strformat, os, sugar, hashes, osproc, tables, strutils, sets, uri, json,
sequtils, setutils, times,
],
with,
chronos,
chronos/[threadsync, asyncproc],
chronicles,
json_serialization,
json_rpc/[errors, servers/socketserver],
regex,
stew/byteutils,
./protocol/[enums, types],
./[suggestapi, utils, nimcheck]
export RegexError
proc getVersionFromNimble(): string =
#We should static run nimble dump instead
const content = staticRead("nimlangserver.nimble")
for v in content.splitLines:
if v.startsWith("version"):
return v.split("=")[^1].strip(chars = {' ', '"'})
return "unknown"
const
RESTART_COMMAND* = "nimlangserver.restart"
RECOMPILE_COMMAND* = "nimlangserver.recompile"
CHECK_PROJECT_COMMAND* = "nimlangserver.checkProject"
FILE_CHECK_DELAY* = 1000
LSPVersion* = getVersionFromNimble()
USE_NIM_CHECK_BY_DEFAULT* = false
NIM_EXPAND_ARC_BY_DEFAULT* = false
NIM_EXPAND_MACRO_BY_DEFAULT* = false
NIM_MAX_NS_PROCESSES* = 1
MaxNimsuggestFails = 10
type
NlsNimsuggestConfig* = ref object of RootObj
projectFile*: string
fileRegex*: string
NlsWorkingDirectoryMaping* = ref object of RootObj
projectFile*: string
directory*: string
NlsInlayTypeHintsConfig* = ref object of RootObj
enable*: Option[bool]
NlsInlayExceptionHintsConfig* = ref object of RootObj
enable*: Option[bool]
hintStringLeft*: Option[string]
hintStringRight*: Option[string]
NlsInlayParameterHintsConfig* = ref object of RootObj
enable*: Option[bool]
NlsInlayHintsConfig* = ref object of RootObj
typeHints*: Option[NlsInlayTypeHintsConfig]
exceptionHints*: Option[NlsInlayExceptionHintsConfig]
parameterHints*: Option[NlsInlayParameterHintsConfig]
NlsNotificationVerbosity* = enum
nvNone = "none"
nvError = "error"
nvWarning = "warning"
nvInfo = "info"
NlsConfig* = ref object of RootObj
projectMapping*: OptionalSeq[NlsNimsuggestConfig]
workingDirectoryMapping*: OptionalSeq[NlsWorkingDirectoryMaping]
checkOnSave*: Option[bool]
nimsuggestPath*: Option[string]
timeout*: Option[int]
autoRestart*: Option[bool]
autoCheckFile*: Option[bool]
autoCheckProject*: Option[bool]
logNimsuggest*: Option[bool]
inlayHints*: Option[NlsInlayHintsConfig]
notificationVerbosity*: Option[NlsNotificationVerbosity]
formatOnSave*: Option[bool]
nimsuggestIdleTimeout*: Option[int] #idle timeout in ms
useNimCheck*: Option[bool]
nimExpandArc*: Option[bool]
nimExpandMacro*: Option[bool]
maxNimsuggestProcesses*: Option[int]
#max number of nimsuggest processes to keep alive. zero means unlimited
nimsuggestTimeout*: Option[int]
#timeout for the nimsuggest startup + initial compilation
nimsuggestMaxMemory*: Option[int]
#memory cap per nimsuggest process in MB. zero means unlimited
useNimTrack*: Option[bool]
NlsFileInfo* = ref object of RootObj
projectFile*: Future[string].Raising([CancelledError, OSError, RegexError])
changed*: bool
fingerTable*: seq[seq[tuple[u16pos, offset: int]]]
cancelFileCheck*: Future[void].Raising([CancelledError])
checkInProgress*: bool
needsChecking*: bool
textDocument*: TextDocumentItem
nimsuggestProject*: string
CommandLineParams* = object
mode*: Option[ServerMode]
transport*: Option[TransportMode]
port*: Port #only for sockets
ServerMode* = enum
lsp = "lsp"
mcp = "mcp"
TransportMode* = enum
stdio = "stdio"
socket = "socket"
PendingRequestState* = enum
prsOnGoing = "OnGoing"
prsCancelled = "Cancelled"
prsComplete = "Complete"
PendingRequest* = object
id*: uint
name*: string
request*: FutureBase
projectFile*: Option[string]
startTime*: DateTime
endTime*: DateTime
state*: PendingRequestState
LanguageServer* = ref object
case serverMode*: ServerMode
of lsp:
lspClientCapabilities*: LspClientCapabilities
lspServerCapabilities*: LspServerCapabilities
lspInitializeParams*: LspInitializeParams
of mcp:
mcpClientCapabilities*: McpClientCapabilities
mcpServerCapabilities*: McpServerCapabilities
mcpInitializeParams*: McpInitializeParams
extensionCapabilities*: set[LspExtensionCapability]
notifyAction*: NotifyAction
callAction*: CallAction
onExit*: OnExitCallback
projectFiles*: Table[string, Project]
nimsuggestCreations*: Table[string, Future[void].Raising([CancelledError])]
openFiles*: Table[string, NlsFileInfo]
workspaceConfiguration*: NlsConfig
#What the client configured us with, or the defaults until it does.
#Set through setWorkspaceConfiguration, read through getWorkspaceConfiguration.
workspaceConfigurationReady*: Future[void].Raising([CancelledError])
#Completed the first time a configuration is known, and never replaced.
inlayHintsRefreshRequest*: Future[JsonNode].Raising([CancelledError, JsonRpcError])
didChangeConfigurationRegistrationRequest*:
Future[JsonNode].Raising([CancelledError, JsonRpcError])
filesWithDiags*: HashSet[string]
nimsuggestInit*: Future[void].Raising([CancelledError, OSError])
lastNimsuggest*: Nimsuggest
isShutdownNimsuggest*: bool
initialized*: bool
#Set once initialize has run. Until then routes can't rely on its state.
isShutdown*: bool
storageDir*: string
nimDumpCache*: Table[string, NimbleDumpInfo] #path to NimbleDumpInfo
entryPoints*: seq[string]
testRunProcess*: Option[AsyncProcessRef]
#There is only one test run process at a time
srv*: RpcServer #Both modes use it to store the routes
pendingRequests*: Table[uint, PendingRequest]
#id to future. Each request is added here so we can cancel them later in the cancelRequest. Only requests, not notifications
transportMode*: TransportMode
served*: Future[void]
projectErrors*: seq[ProjectError]
lastStatusSent: JsonString
failTable*: Table[string, int]
#Project file to fail count
#List of errors (crashes) nimsuggest has had since the lsp session started
checkInProgress*: bool
token: uint
Certainty* = enum
None
Folder
Cfg
Nimble
NimbleDumpInfo* = object
srcDir*: string
name*: string
nimDir*: Option[string]
nimblePath*: Option[string]
entryPoints*: seq[string] #when it's empty, means the nimble version doesnt dump it.
OnExitCallback* = proc(): Future[void] {.async: (raises: []).}
#To be called when the server is shutting down
NotifyAction* =
proc(name: string, params: JsonString): Future[void] {.async: (raises: []).}
#Send a notification to the client
CallAction* = proc(name: string, params: JsonString): Future[JsonNode] {.
async: (raises: [CancelledError, JsonRpcError])
.} #Send a request to the client
macro `%*`*(t: untyped, inputStream: untyped): untyped =
## Typed JSON literal: `T %* {...}`. The literal is written in code, so a
## failing conversion is a programming error, not something to handle.
let conv =
newCall(bindSym("to", brOpen), newCall(bindSym("%*", brOpen), inputStream), t)
result = quote:
try:
`conv`
except ValueError:
raiseAssert getCurrentExceptionMsg()
proc notify*[T](ls: LanguageServer, name: string, params: T) =
asyncSpawn ls.notifyAction(name, JsonString LspJson.encode(params))
proc call*[T](
ls: LanguageServer, name: string, params: T
): Future[JsonNode] {.async: (raw: true, raises: [CancelledError, JsonRpcError]).} =
ls.callAction(name, JsonString LspJson.encode(params))
proc initLs*(params: CommandLineParams, storageDir: string): LanguageServer =
LanguageServer(
workspaceConfiguration: NlsConfig(),
workspaceConfigurationReady: Future[void].Raising([CancelledError]).init("initLs"),
filesWithDiags: initHashSet[string](),
serverMode: params.mode.get(),
transportMode: params.transport.get(stdio),
openFiles: initTable[string, NlsFileInfo](),
storageDir: storageDir,
extensionCapabilities: LspExtensionCapability.items.toSet,
)
proc createProgressToken*(ls: LanguageServer): string =
inc ls.token
"token-" & $ls.token
proc getNimbleEntryPoints*(
dumpInfo: NimbleDumpInfo, nimbleProjectPath: string
): seq[string] =
if dumpInfo.entryPoints.len > 0:
result = dumpInfo.entryPoints.mapIt(nimbleProjectPath / it)
else:
#Nimble doesnt include the entry points, returning the nimble project file as the entry point
let sourceDir = nimbleProjectPath / dumpInfo.srcDir
result = @[sourceDir / (dumpInfo.name & ".nim")]
result = result.filterIt(it.fileExists)
func typeHintsEnabled*(cnf: NlsConfig): bool =
result = true
if cnf.inlayHints.isSome and cnf.inlayHints.get.typeHints.isSome and
cnf.inlayHints.get.typeHints.get.enable.isSome:
result = cnf.inlayHints.get.typeHints.get.enable.get
func exceptionHintsEnabled*(cnf: NlsConfig): bool =
result = false
if cnf.inlayHints.isSome and cnf.inlayHints.get.exceptionHints.isSome and
cnf.inlayHints.get.exceptionHints.get.enable.isSome:
result = cnf.inlayHints.get.exceptionHints.get.enable.get
func parameterHintsEnabled*(cnf: NlsConfig): bool =
result = true
if cnf.inlayHints.isSome and cnf.inlayHints.get.parameterHints.isSome and
cnf.inlayHints.get.parameterHints.get.enable.isSome:
result = cnf.inlayHints.get.parameterHints.get.enable.get
func inlayHintsEnabled*(cnf: NlsConfig): bool =
typeHintsEnabled(cnf) or exceptionHintsEnabled(cnf) or parameterHintsEnabled(cnf)
proc supportSignatureHelp*(cc: LspClientCapabilities): bool =
if cc.isNil:
return false
let caps = cc.textDocument
caps.isSome and caps.get.signatureHelp.isSome
proc getNimbleDumpInfo*(
ls: LanguageServer, nimbleFile: string, workingDir = ""
): Future[NimbleDumpInfo] {.async: (raises: [CancelledError]).} =
if nimbleFile in ls.nimDumpCache:
return ls.nimDumpCache.getOrDefault(nimbleFile)
debug "nimble dump starting",
nimbleFile = nimbleFile, nimbleDir = getEnv("NIMBLE_DIR")
var process: AsyncProcessRef
try:
process = await startProcess(
"nimble",
workingDir = nimbleFile.parentDir(),
arguments = @["dump"],
options = {UsePath},
stderrHandle = ProcessStreamHandle(), # None => chronos doesn't
# manage stderr, child inherits ours
stdoutHandle = AsyncProcess.Pipe,
)
let info = string.fromBytes(process.stdoutStream.read().await)
for line in info.splitLines:
if line.startsWith("srcDir"):
result.srcDir = line[(1 + line.find '"') ..^ 2]
if line.startsWith("name"):
result.name = line[(1 + line.find '"') ..^ 2]
if line.startsWith("nimDir"):
result.nimDir = some line[(1 + line.find '"') ..^ 2]
if line.startsWith("nimblePath"):
result.nimblePath = some line[(1 + line.find '"') ..^ 2]
if line.startsWith("entryPoints"):
result.entryPoints =
line[(1 + line.find '"') ..^ 2].split(',').mapIt(it.strip(chars = {' ', '"'}))
var nimbleFile = nimbleFile
if nimbleFile == "" and result.nimblePath.isSome:
nimbleFile = result.nimblePath.get
if nimbleFile != "":
ls.nimDumpCache[nimbleFile] = result
debug "nimble dump finished",
nimbleFile = nimbleFile, nimDir = result.nimDir.get("")
except OSError, IOError, AsyncProcessError, AsyncStreamError:
debug "Failed to get nimble dump info",
nimbleFile = nimbleFile, err = getCurrentExceptionMsg()
finally:
if process != nil:
await shutdownChildProcess(process)
proc parseWorkspaceConfiguration*(conf: JsonNode): NlsConfig =
try:
if conf.kind == JObject and conf["settings"].kind == JObject:
let nimSettings = conf["settings"]["nim"]
if nimSettings.kind == JNull:
return NlsConfig() #the client has no settings for us
return nimSettings.to(NlsConfig)
except ValueError:
discard
try:
let nlsConfig: seq[NlsConfig] = (%conf).to(seq[NlsConfig])
result =
if nlsConfig.len > 0 and nlsConfig[0] != nil:
nlsConfig[0]
else:
NlsConfig()
except ValueError:
debug "Failed to parse the configuration.", error = getCurrentExceptionMsg()
result = NlsConfig()
proc setWorkspaceConfiguration*(ls: LanguageServer, conf: JsonNode) {.raises: [].} =
ls.workspaceConfiguration = parseWorkspaceConfiguration(conf)
if not ls.workspaceConfigurationReady.finished:
ls.workspaceConfigurationReady.complete()
proc getWorkspaceConfiguration*(ls: LanguageServer): NlsConfig {.raises: [].} =
#TODO review and handle project specific confs when received instead of reliying in this func
if ls.workspaceConfiguration.isNil:
NlsConfig()
else:
ls.workspaceConfiguration
proc getAndWaitForWorkspaceConfiguration*(
ls: LanguageServer
): Future[NlsConfig] {.async: (raises: [CancelledError]).} =
await ls.workspaceConfigurationReady.join()
ls.getWorkspaceConfiguration()
proc showMessage*(
ls: LanguageServer, message: string, typ: MessageType
) {.raises: [].} =
proc notify() =
ls.notify(
"window/showMessage", ShowMessageParams(`type`: typ.int, message: message)
)
let verbosity = ls.getWorkspaceConfiguration.notificationVerbosity.get(
NlsNotificationVerbosity.nvInfo
)
debug "ShowMessage ", message = message
case verbosity
of nvInfo:
notify()
of nvWarning:
if typ.int <= MessageType.Warning.int:
notify()
of nvError:
if typ == MessageType.Error:
notify()
else:
discard
proc applyEdit*(
ls: LanguageServer, params: ApplyWorkspaceEditParams
): Future[ApplyWorkspaceEditResponse] {.
async: (raises: [CancelledError, ValueError, JsonRpcError])
.} =
let res = await ls.call("workspace/applyEdit", params)
res.to(ApplyWorkspaceEditResponse)
proc toPendingRequestStatus(pr: PendingRequest): PendingRequestStatus =
result.time =
case pr.state
of prsOnGoing:
$(now() - pr.startTime)
else:
$(pr.endTime - pr.startTime)
result.name = pr.name
result.projectFile = pr.projectFile.get("")
result.state = $pr.state
# https://microsoft.github.io/language-server-protocol/specifications/lsp/3.18/specification/#responseMessage
proc checkInitialized*(ls: LanguageServer) {.raises: [ApplicationError].} =
if not ls.initialized:
raise (ref ApplicationError)(
code: ErrorCode.ServerNotInitialized.int, msg: "Server not initialized"
)
proc filesServedBy(ls: LanguageServer, projectFile: string): seq[string] =
for uri, file in ls.openFiles:
if file.nimsuggestProject == projectFile:
result.add uri
proc getLspStatus*(ls: LanguageServer): NimLangServerStatus {.raises: [].} =
result.lspPath = getAppFilename()
result.version = LSPVersion
result.extensionCapabilities = ls.extensionCapabilities.toSeq
for project in ls.projectFiles.values:
let ns = project.ns
if ns != nil:
var nsStatus = NimsuggestStatus(
projectFile: project.file,
capabilities: ns.capabilities.toSeq,
version: ns.version,
path: ns.nimsuggestPath,
port: ns.port,
)
nsStatus.openFiles = ls.filesServedBy(project.file)
result.nimsuggestInstances.add nsStatus
for openFile in ls.openFiles.keys:
let openFilePath = openFile.uriToPath
result.openFiles.add openFilePath
result.pendingRequests = ls.pendingRequests.values.toSeq.map(toPendingRequestStatus)
result.projectErrors = ls.projectErrors
proc sendStatusChanged*(ls: LanguageServer) {.raises: [].} =
let status = JsonString LspJson.encode(ls.getLspStatus())
if status != ls.lastStatusSent:
ls.notify("extension/statusUpdate", status)
ls.lastStatusSent = status
proc waitProjectFile*(
file: NlsFileInfo
): Future[string] {.async: (raises: [CancelledError, OSError, RegexError]).} =
## Wait without allowing a cancelled request to cancel the shared future.
await file.projectFile.join()
try:
file.projectFile.read()
except FuturePendingError:
raiseAssert "project file future remained pending after join"
proc addProjectFileToPendingRequest*(
ls: LanguageServer, id: uint, uri: string
) {.async: (raises: []).} =
try:
if id in ls.pendingRequests:
var projectFile = uri.uriToPath()
if projectFile notin ls.projectFiles:
if uri in ls.openFiles:
projectFile = await ls.openFiles[uri].waitProjectFile()
ls.pendingRequests[id].projectFile = some projectFile
ls.sendStatusChanged
except CancelledError:
discard
except KeyError, OSError, RegexError:
error "addProjectFileToPendingRequest failed",
uri = uri, msg = getCurrentExceptionMsg()
proc requiresDynamicRegistrationForDidChangeConfiguration(ls: LanguageServer): bool =
ls.lspClientCapabilities.workspace.isSome and
ls.lspClientCapabilities.workspace.get.didChangeConfiguration.isSome and
ls.lspClientCapabilities.workspace.get.didChangeConfiguration.get.dynamicRegistration.get(
false
)
proc supportsConfigurationRequest(ls: LanguageServer): bool =
ls.lspClientCapabilities.workspace.isSome and
ls.lspClientCapabilities.workspace.get.configuration.get(false)
proc usePullConfigurationModel*(ls: LanguageServer): bool =
ls.requiresDynamicRegistrationForDidChangeConfiguration and
ls.supportsConfigurationRequest
proc inlayExceptionHintsConfigurationEquals*(a, b: NlsInlayHintsConfig): bool =
if a.exceptionHints.isSome and b.exceptionHints.isSome:
let
ae = a.exceptionHints.get
be = b.exceptionHints.get
result =
(ae.enable == be.enable) and (ae.hintStringLeft == be.hintStringLeft) and
(ae.hintStringRight == be.hintStringRight)
else:
result = a.exceptionHints.isSome == b.exceptionHints.isSome
proc inlayExceptionHintsConfigurationEquals*(a, b: NlsConfig): bool =
if a.inlayHints.isSome and b.inlayHints.isSome:
result = inlayExceptionHintsConfigurationEquals(a.inlayHints.get, b.inlayHints.get)
else:
result = a.inlayHints.isSome == b.inlayHints.isSome
proc inlayHintsConfigurationEquals*(a, b: NlsConfig): bool =
proc inlayTypeHintsConfigurationEquals(a, b: NlsInlayHintsConfig): bool =
if a.typeHints.isSome and b.typeHints.isSome:
result = a.typeHints.get.enable == b.typeHints.get.enable
else:
result = a.typeHints.isSome == b.typeHints.isSome
proc inlayHintsConfigurationEquals(a, b: NlsInlayHintsConfig): bool =
result =
inlayTypeHintsConfigurationEquals(a, b) and
inlayExceptionHintsConfigurationEquals(a, b)
if a.inlayHints.isSome and b.inlayHints.isSome:
result = inlayHintsConfigurationEquals(a.inlayHints.get, b.inlayHints.get)
else:
result = a.inlayHints.isSome == b.inlayHints.isSome
proc getNimVersion(nimDir: string): string {.raises: [OSError, IOError].} =
let cmd =
if nimDir == "":
"nim --version"
else:
nimDir / "nim --version"
let info = execProcess(cmd)
const NimCompilerVersion = "Nim Compiler Version "
for line in info.splitLines:
if line.startsWith(NimCompilerVersion):
return line
proc getNimsuggestPathAndVersion(
ls: LanguageServer, conf: NlsConfig, workingDir: string
): Future[(string, string)] {.async: (raises: [CancelledError, OSError, IOError]).} =
let nimbleFiles = walkFiles(workingDir / "*.nimble").toSeq
let nimbleDumpInfo =
if nimbleFiles.len > 0:
await ls.getNimbleDumpInfo(nimbleFiles[0], workingDir)
else:
await ls.getNimbleDumpInfo("", workingDir)
let nimDir = nimbleDumpInfo.nimDir.get ""
var nimsuggestPath = expandTilde(conf.nimsuggestPath.get(""))
var nimVersion = ""
if nimsuggestPath == "":
if nimDir != "" and nimDir.dirExists:
nimVersion = getNimVersion(nimDir) & " from " & nimDir
nimsuggestPath = nimDir / "nimsuggest"
else:
nimVersion = getNimVersion("")
nimsuggestPath = findExe "nimsuggest"
else:
nimVersion = getNimVersion(nimsuggestPath.parentDir)
# ls.showMessage(fmt "Using {nimVersion}", MessageType.Info)
debug "Using {nimVersion}", nimVersion = nimVersion
(nimsuggestPath, nimVersion)
proc getNimPath*(
ls: LanguageServer, conf: NlsConfig, workingDir = ""
): Future[Option[string]] {.async: (raises: [CancelledError, OSError, IOError]).} =
if conf.nimsuggestPath.isSome and conf.nimsuggestPath.get().fileExists():
some(conf.nimsuggestPath.get.parentDir / "nim")
else:
let (nimsuggestPath, _) = await ls.getNimsuggestPathAndVersion(conf, workingDir)
let path =
if nimsuggestPath.fileExists():
nimsuggestPath.parentDir / "nim"
else:
findExe "nim"
if path != "":
some(path)
else:
warn "Failed to find nim path"
none(string)
proc getProjectFileAutoGuess*(
ls: LanguageServer, fileUri: string
): Future[string] {.async: (raises: [CancelledError, OSError]).} =
let file = fileUri.decodeUrl
debug "Auto-guessing project file for", file = file
result = file
let (dir, _, _) = result.splitFile()
var
path = dir
certainty = Certainty.None
up = 0
let conf = ls.getWorkspaceConfiguration()
let maxNimsuggestProcesses = conf.maxNimsuggestProcesses.get(NIM_MAX_NS_PROCESSES)
# When using only one nimsuggest process, we should not search for parent projects
# as this will cause all files to be opened in the same nimsuggest process.
let maxUp = if maxNimsuggestProcesses == 1: 0 else: 2
while path.len > 0 and path != "/" and up < maxUp:
let
(dir, fname, ext) = path.splitFile()
current = fname & ext
if fileExists(path / current.addFileExt(".nim")) and certainty <= Folder:
result = path / current.addFileExt(".nim")
certainty = Folder
if fileExists(path / current.addFileExt(".nim")) and (
fileExists(path / current.addFileExt(".nim.cfg")) or
fileExists(path / current.addFileExt(".nims"))
) and certainty <= Cfg:
result = path / current.addFileExt(".nim")
certainty = Cfg
if certainty <= Nimble:
for nimble in walkFiles(path / "*.nimble"):
let dumpInfo = await ls.getNimbleDumpInfo(nimble)
let name = dumpInfo.name
let sourceDir = path / dumpInfo.srcDir
let projectFile = sourceDir / (name & ".nim")
if sourceDir.len != 0 and name.len != 0 and file.isRelTo(sourceDir) and
fileExists(projectFile):
debug "Found nimble project", projectFile = projectFile
result = projectFile
certainty = Nimble
return
if path == dir:
break
path = dir
inc up
proc getRootPath*(ip: LspInitializeParams): string {.raises: [OSError].} =
if ip.rootUri.isNone or ip.rootUri.get == "":
if ip.rootPath.isSome and ip.rootPath.get != "":
return ip.rootPath.get
else:
return getCurrentDir().pathToUri.uriToPath
ip.rootUri.get.uriToPath
proc getRootPath*(ip: McpInitializeParams): string {.raises: [OSError].} =
getCurrentDir().pathToUri.uriToPath
proc getWorkingDir*(
ls: LanguageServer, path: string
): Future[string] {.async: (raises: [OSError]).} =
let rootPath =
case ls.serverMode
of lsp: ls.lspInitializeParams.getRootPath
of mcp: ls.mcpInitializeParams.getRootPath
let
pathRelativeToRoot = path.tryRelativeTo(rootPath)
mapping = ls.getWorkspaceConfiguration().workingDirectoryMapping.get(@[])
result = rootPath
for m in mapping:
if pathRelativeToRoot.isSome and m.projectFile == pathRelativeToRoot.get():
result = rootPath / m.directory
break
proc progressSupported(ls: LanguageServer): bool =
result = ls.lspInitializeParams.capabilities.window
.get(ClientCapabilities_window()).workDoneProgress
.get(false)
proc progress*(ls: LanguageServer, token, kind: string, title = "") =
if ls.progressSupported:
ls.notify(
"$/progress",
ProgressParams(token: token, value: some %*{"kind": kind, "title": title}),
)
proc workDoneProgressCreate*(ls: LanguageServer, token: string) =
if ls.progressSupported:
discard ls.call("window/workDoneProgress/create", ProgressParams(token: token))
proc cancelPendingFileChecks*(ls: LanguageServer, nimsuggest: Nimsuggest) =
# stop all checks on file level if we are going to run checks on project
# level.
for uri in ls.filesServedBy(nimsuggest.project.file):
let fileData = ls.openFiles.getOrDefault(uri)
if fileData != nil:
let cancelFileCheck = fileData.cancelFileCheck
if cancelFileCheck != nil and not cancelFileCheck.finished:
cancelFileCheck.complete()
fileData.needsChecking = false
proc uriStorageLocation*(ls: LanguageServer, uri: string): string =
ls.storageDir / (hash(uri).toHex & ".nim")
proc uriToStash*(ls: LanguageServer, uri: string): string =
let file = ls.openFiles.getOrDefault(uri)
if file != nil and file.changed:
uriStorageLocation(ls, uri)
else:
""
proc toUtf16Pos*(
ls: LanguageServer, uri: string, line: int, utf8Pos: int
): Option[int] =
let file = ls.openFiles.getOrDefault(uri)
if file != nil and line in 0 ..< file.fingerTable.len:
let utf16Pos = file.fingerTable[line].utf8to16(utf8Pos)
return some(utf16Pos)
else:
return none(int)
proc toUtf16Pos*(suggest: Suggest, ls: LanguageServer): Suggest =
result = suggest
let uri = pathToUri(suggest.filePath)
let pos = toUtf16Pos(ls, uri, suggest.line - 1, suggest.column)
if pos.isSome:
result.column = pos.get()
proc toUtf16Pos*(
suggest: SuggestInlayHint, ls: LanguageServer, uri: string
): SuggestInlayHint =
result = suggest
let pos = toUtf16Pos(ls, uri, suggest.line - 1, suggest.column)
if pos.isSome:
result.column = pos.get()
proc toUtf16Pos*(checkResult: CheckResult, ls: LanguageServer): CheckResult =
result = checkResult
let uri = pathToUri(checkResult.file)
let pos = toUtf16Pos(ls, uri, checkResult.line - 1, checkResult.column)
if pos.isSome:
result.column = pos.get()
for i in 0 ..< result.stacktrace.len:
let stPos =
toUtf16Pos(ls, uri, result.stacktrace[i].line - 1, result.stacktrace[i].column)
if stPos.isSome:
result.stacktrace[i].column = stPos.get()
proc range*(startLine, startCharacter, endLine, endCharacter: int): Range =
return
Range %* {
"start": {"line": startLine, "character": startCharacter},
"end": {"line": endLine, "character": endCharacter},
}
proc toLabelRange*(suggest: Suggest): Range =
with suggest:
return range(line - 1, column, line - 1, column + utf16Len(qualifiedPath[^1]))
proc toDiagnostic(suggest: Suggest): Diagnostic =
with suggest:
let
textStart = doc.find('\'')
textEnd = doc.rfind('\'')
endColumn =
if textStart >= 0 and textEnd > textStart:
column + utf16Len(doc[textStart + 1 ..< textEnd])
else:
column + 1
return
Diagnostic %* {
"uri": pathToUri(filePath),
"range": range(line - 1, column, line - 1, endColumn),
"severity":
case forth
of "Error": DiagnosticSeverity.Error.int
of "Hint": DiagnosticSeverity.Hint.int
of "Warning": DiagnosticSeverity.Warning.int
else: DiagnosticSeverity.Error.int
,
"message": doc,
"source": "nim",
"code": "nimsuggest chk",
}
proc toDiagnostic(checkResult: CheckResult): Diagnostic =
let
textStart = checkResult.msg.find('\'')
textEnd = checkResult.msg.rfind('\'')
endColumn =
if textStart >= 0 and textEnd >= 0 and textEnd > textStart:
checkResult.column + utf16Len(checkResult.msg[textStart + 1 ..< textEnd])
else:
checkResult.column + 1
return
Diagnostic %* {
"uri": pathToUri(checkResult.file),
"range": range(
checkResult.line - 1,
max(0, checkResult.column),
checkResult.line - 1,
max(0, endColumn),
),
"severity":
case checkResult.severity
of "Error": DiagnosticSeverity.Error.int
of "Hint": DiagnosticSeverity.Hint.int
of "Warning": DiagnosticSeverity.Warning.int
else: DiagnosticSeverity.Error.int
,
"message": checkResult.msg,
"source": "nim",
"code": "nim check",
}
proc sendDiagnostics*(
ls: LanguageServer, diagnostics: seq[Suggest] | seq[CheckResult], path: string
) =
trace "Sending diagnostics", count = diagnostics.len, path = path
let params =
PublishDiagnosticsParams %* {
"uri": pathToUri(path),
"diagnostics": diagnostics.map(x => x.toUtf16Pos(ls).toDiagnostic),
}
ls.notify("textDocument/publishDiagnostics", params)
if diagnostics.len != 0:
ls.filesWithDiags.incl path
else:
ls.filesWithDiags.excl path
proc warnIfUnknown*(
ls: LanguageServer, ns: Nimsuggest, uri: string, projectFile: string
): Future[void] {.async: (raises: [CancelledError]).} =
let path = uri.uriToPath
let isFileKnown = await ns.isKnown(path)
if not isFileKnown and not ns.canHandleUnknown:
ls.showMessage(
fmt """{path} is not compiled as part of project {projectFile}.
In orde to get the IDE features working you must either configure nim.projectMapping or import the module.""",
MessageType.Warning,
)
proc createOrRestartNimsuggest*(
ls: LanguageServer, projectFile: string, uri = ""
): Future[void] {.async: (raw: true, raises: [CancelledError]).}
proc isLiveNimsuggestProject(ls: LanguageServer, projectFile: string): bool =
projectFile in ls.projectFiles or projectFile in ls.nimsuggestCreations
proc liveNimsuggestProjects*(ls: LanguageServer): seq[string] =
## Running + starting instances.
for entryPoint in ls.entryPoints:
if ls.isLiveNimsuggestProject(entryPoint) and entryPoint notin result:
result.add entryPoint
for projectFile in ls.projectFiles.keys:
if projectFile notin result:
result.add projectFile
for projectFile in ls.nimsuggestCreations.keys:
if projectFile notin result:
result.add projectFile
proc canSpawnNimsuggest(ls: LanguageServer): bool =
let nsCount = ls.liveNimsuggestProjects.len
let conf = ls.getWorkspaceConfiguration()
let maxNimsuggestProcesses = conf.maxNimsuggestProcesses.get(NIM_MAX_NS_PROCESSES)
result = maxNimsuggestProcesses == 0 or nsCount < maxNimsuggestProcesses
debug "canSpawnNimsuggest",
result = result, nsCount = nsCount, maxNimsuggestProcesses = maxNimsuggestProcesses
proc reuseLiveNimsuggestProject(ls: LanguageServer): string =
let live = ls.liveNimsuggestProjects
if live.len > 0:
result = live[0]
debug "Reached the maximum instances of nimsuggest, reusing the first nimsuggest instance",
project = result
proc mappedProjectFiles(ls: LanguageServer): seq[string] {.raises: [OSError].} =
let rootPath =
case ls.serverMode
of mcp:
ls.mcpInitializeParams.getRootPath()
of lsp:
ls.lspInitializeParams.getRootPath()
ls.getWorkspaceConfiguration().projectMapping.get(@[]).mapIt(
rootPath / it.projectFile
)
proc nimsuggestProjectFor(
ls: LanguageServer, projectFile: string
): string {.raises: [OSError].} =
if ls.isLiveNimsuggestProject(projectFile) or projectFile in ls.mappedProjectFiles() or
ls.canSpawnNimsuggest():
projectFile
else:
ls.reuseLiveNimsuggestProject()
proc initNimsuggestInstances*(
ls: LanguageServer, rootPath: string
) {.async: (raises: [CancelledError, OSError]).} =
if rootPath == "":
return
let nimbleFiles = walkFiles(rootPath / "*.nimble").toSeq
if nimbleFiles.len > 0:
let nimbleFile = nimbleFiles[0]
let nimbleDumpInfo = await ls.getNimbleDumpInfo(nimbleFile)
ls.entryPoints = nimbleDumpInfo.getNimbleEntryPoints(rootPath)
for entryPoint in ls.entryPoints:
if not ls.isLiveNimsuggestProject(entryPoint) and ls.canSpawnNimsuggest():
debug "Starting nimsuggest for entry point ", entry = entryPoint
await ls.createOrRestartNimsuggest(entryPoint)
proc failoverProject(ls: LanguageServer, projectFile: string): string =
if ls.failTable.getOrDefault(projectFile, 0) < MaxNimsuggestFails:
projectFile
else:
let others = ls.projectFiles.keys.toSeq.filterIt(
it != projectFile and ls.failTable.getOrDefault(it, 0) < MaxNimsuggestFails
)
if others.len > 0:
others[0]
else:
""
proc hasServingNimsuggest(ls: LanguageServer, file: NlsFileInfo): bool =
file.nimsuggestProject != "" and ls.isLiveNimsuggestProject(file.nimsuggestProject) and
ls.failTable.getOrDefault(file.nimsuggestProject, 0) < MaxNimsuggestFails
proc getNimsuggestInner(
ls: LanguageServer, uri: string
): Future[Nimsuggest] {.async: (raises: [CancelledError, OSError, RegexError]).} =
let file = ls.openFiles.getOrDefault(uri)
if file == nil:
debug "File is no longer open", uri = uri
return nil
let projectFile = await file.waitProjectFile()
if not ls.hasServingNimsuggest(file):
let ownProject = ls.nimsuggestProjectFor(projectFile)
file.nimsuggestProject = ls.failoverProject(ownProject)
if file.nimsuggestProject notin ["", ownProject]:
debug "Reusing nimsuggest instance for",
uri = uri, projectFile = file.nimsuggestProject
let nsProject = file.nimsuggestProject
if nsProject == "":
return nil
if not ls.projectFiles.hasKey(nsProject):
debug "Creating new nimsuggest instance", uri = uri, projectFile = nsProject
await ls.createOrRestartNimsuggest(nsProject, uri)
# Wait a bit to allow nimsuggest to start
await sleepAsync(10)
# Check multiple times with small delays
var attempts = 0
const maxAttempts = 10
while attempts < maxAttempts:
let project = ls.projectFiles.getOrDefault(nsProject)
if project != nil:
ls.lastNimsuggest = project.ns
return project.ns
inc attempts
if attempts < maxAttempts:
await sleepAsync(100)
debug "Waiting for nimsuggest to initialize",
uri = uri, projectFile = nsProject, attempt = attempts
debug "Failed to get nimsuggest after waiting", uri = uri, projectFile = nsProject
return nil
proc tryGetNimsuggest*(
ls: LanguageServer, uri: string
): Future[Option[Nimsuggest]] {.
async: (raises: [CancelledError, OSError, IOError, RegexError])
.}
proc checkFile*(
ls: LanguageServer, file: NlsFileInfo
): Future[void] {.
async: (
raises: [
CancelledError, AsyncProcessError, AsyncStreamError, OSError, IOError, RegexError,
NimsuggestError,
]
)
.}
proc didCloseFile*(
ls: LanguageServer, uri: string
): Future[void] {.async: (raises: []).} =
debug "Closed the following document:", uri = uri
let file = ls.openFiles.getOrDefault(uri)
ls.openFiles.del uri
if file != nil and file.changed:
# check the file if it is closed but not saved.
traceAsyncErrors ls.checkFile(file)
proc getProjectFile*(
fileUri: string, ls: LanguageServer
): Future[string] {.async: (raises: [CancelledError, OSError, RegexError]).}
proc getProjectFileAfterStartup(
ls: LanguageServer, fileUri: string
): Future[string] {.async: (raises: [CancelledError, OSError, RegexError]).} =
## Resolve files after Nimble entry-point startup has completed. Otherwise
## the single-process limit can make auto-guessing fall back to the opened
## file while the intended entry-point nimsuggest is still compiling.
if not ls.nimsuggestInit.isNil: