Skip to content

Commit 1da21da

Browse files
authored
Applies nph to src files (#246)
1 parent f62cd24 commit 1da21da

File tree

10 files changed

+449
-369
lines changed

10 files changed

+449
-369
lines changed

asyncprocmonitor.nim

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ type Callback* = proc() {.closure, gcsafe, raises: [].}
1212
when defined(windows):
1313
import winlean
1414

15-
proc hookAsyncProcMonitor*(pid: int, cb: Callback) = discard
16-
addProcess2(pid, (arg: pointer) => cb())
15+
proc hookAsyncProcMonitor*(pid: int, cb: Callback) =
16+
discard addProcess2(pid, (arg: pointer) => cb())
1717

1818
elif defined(posix):
1919
proc hookAsyncProcMonitor*(pid: int, cb: Callback) =

ls.nim

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -675,9 +675,9 @@ proc onErrorCallback(args: (LanguageServer, string), project: Project) =
675675
finally:
676676
if project.file != "":
677677
ls.projectErrors.add ProjectError(
678-
projectFile: project.file,
678+
projectFile: project.file,
679679
errorMessage: project.errorMessage,
680-
lastKnownCmd: project.lastCmd
680+
lastKnownCmd: project.lastCmd,
681681
)
682682
ls.sendStatusChanged()
683683

@@ -820,7 +820,9 @@ proc maybeRequestConfigurationFromClient*(ls: LanguageServer) =
820820
debug "Client does not support workspace/configuration"
821821
ls.workspaceConfiguration.complete(newJArray())
822822

823-
proc getCharacter*(ls: LanguageServer, uri: string, line: int, character: int): Option[int] =
823+
proc getCharacter*(
824+
ls: LanguageServer, uri: string, line: int, character: int
825+
): Option[int] =
824826
if uri in ls.openFiles and line < ls.openFiles[uri].fingerTable.len:
825827
return some ls.openFiles[uri].fingerTable[line].utf16to8(character)
826828
else:

lstransports.nim

Lines changed: 46 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,12 @@ import std/[syncio, os, json, strutils, strformat, streams, oids, sequtils, time
44
import ls, utils
55
import protocol/types, chronos/threadsync
66

7-
type
7+
type
88
LspClientResponse* = object
99
jsonrpc*: JsonRPC2
1010
id*: string
1111
result*: JsonNode
12-
12+
1313
Rpc* = proc(params: RequestParamsRx): Future[JsonString] {.gcsafe, raises: [].}
1414

1515
template flavorUsesAutomaticObjectSerialization(T: type JrpcSys): bool =
@@ -40,14 +40,13 @@ proc toJson*(params: RequestParamsRx): JsonNode =
4040
for p in params.positional:
4141
result.add parseJson($p)
4242

43-
proc wrapRpc*[T](
44-
fn: proc(params: T): Future[auto] {.gcsafe, raises: [].}
45-
): Rpc =
43+
proc wrapRpc*[T](fn: proc(params: T): Future[auto] {.gcsafe, raises: [].}): Rpc =
4644
return proc(params: RequestParamsRx): Future[JsonString] {.gcsafe, async.} =
4745
var val = params.to(T)
4846
when typeof(fn(val)) is Future[void]: #Notification
4947
await fn(val)
50-
return JsonString("{}") #Client doesnt expect a response. Handled in processMessage
48+
return
49+
JsonString("{}") #Client doesnt expect a response. Handled in processMessage
5150
else:
5251
let res = await fn(val)
5352
return JsonString($(%*res))
@@ -66,21 +65,23 @@ proc wrapRpc*[T](
6665
return JsonString($(%*res))
6766
6867
proc addRpcToCancellable*(ls: LanguageServer, rpc: Rpc): Rpc =
69-
return proc(params: RequestParamsRx): Future[JsonString] {.gcsafe, raises:[].} =
68+
return proc(params: RequestParamsRx): Future[JsonString] {.gcsafe, raises: [].} =
7069
try:
7170
let idRequest = get[uint](params, "idRequest")
7271
let name = get[string](params, "method")
73-
ls.pendingRequests[idRequest] = PendingRequest(id: idRequest, name: name, startTime: now(), state: prsOnGoing)
72+
ls.pendingRequests[idRequest] =
73+
PendingRequest(id: idRequest, name: name, startTime: now(), state: prsOnGoing)
7474
ls.sendStatusChanged
7575
var fut = rpc(params)
76-
ls.pendingRequests[idRequest].request = fut #we need to add it before because the rpc may access to the pendingRequest to set the projectFile
77-
fut.addCallback proc (d: pointer) =
76+
ls.pendingRequests[idRequest].request = fut
77+
#we need to add it before because the rpc may access to the pendingRequest to set the projectFile
78+
fut.addCallback proc(d: pointer) =
7879
try:
7980
ls.pendingRequests[idRequest].state = prsComplete
8081
ls.pendingRequests[idRequest].endTime = now()
8182
ls.sendStatusChanged
8283
except KeyError:
83-
error "Error completing pending requests. Id not found in pending requests"
84+
error "Error completing pending requests. Id not found in pending requests"
8485
return fut
8586
except KeyError as ex:
8687
error "IdRequest not found in the request params"
@@ -89,36 +90,36 @@ proc addRpcToCancellable*(ls: LanguageServer, rpc: Rpc): Rpc =
8990
error "Error adding request to cancellable requests"
9091
writeStackTrace(ex)
9192
92-
9393
proc processContentLength*(inputStream: FileStream): string =
9494
result = inputStream.readLine()
9595
if result.startsWith(CONTENT_LENGTH):
9696
let parts = result.split(" ")
9797
let length = parseInt(parts[1])
9898
discard inputStream.readLine() # skip the \r\n
9999
result = newString(length)
100-
for i in 0..<length:
100+
for i in 0 ..< length:
101101
result[i] = inputStream.readChar()
102102
else:
103103
error "No content length \n"
104104

105-
proc processContentLength*(transport: StreamTransport, error: bool = true): Future[string] {.async:(raises:[]).} =
105+
proc processContentLength*(
106+
transport: StreamTransport, error: bool = true
107+
): Future[string] {.async: (raises: []).} =
106108
try:
107109
result = await transport.readLine()
108110
if result.startsWith(CONTENT_LENGTH):
109111
let parts = result.split(" ")
110112
let length = parseInt(parts[1])
111113
discard await transport.readLine() # skip the \r\n
112114
result = (await transport.read(length)).mapIt($(it.char)).join()
113-
114115
else:
115116
if error:
116117
error "No content length \n"
117118
except TransportError as ex:
118119
if error:
119120
error "Error reading content length", msg = ex.msg
120121
except CatchableError as ex:
121-
if error:
122+
if error:
122123
error "Error reading content length", msg = ex.msg
123124

124125
proc readStdin*(ctx: ptr ReadStdinContext) {.thread.} =
@@ -130,14 +131,14 @@ proc readStdin*(ctx: ptr ReadStdinContext) {.thread.} =
130131
discard ctx.onStdReadSignal.fireSync()
131132
discard ctx.onMainReadSignal.waitSync()
132133

133-
proc wrapContentWithContentLenght*(content: string): string =
134+
proc wrapContentWithContentLenght*(content: string): string =
134135
let contentLenght = content.len + 1
135-
&"{CONTENT_LENGTH}{contentLenght}{CRLF}{CRLF}{content}\n"
136+
&"{CONTENT_LENGTH}{contentLenght}{CRLF}{CRLF}{content}\n"
136137

137138
proc writeOutput*(ls: LanguageServer, content: JsonNode) =
138139
let res = wrapContentWithContentLenght($content)
139140
try:
140-
case ls.transportMode:
141+
case ls.transportMode
141142
of stdio:
142143
ls.outStream.write(res)
143144
ls.outStream.flush()
@@ -150,7 +151,7 @@ proc runRpc(ls: LanguageServer, req: RequestRx, rpc: RpcProc): Future[void] {.as
150151
try:
151152
let res = await rpc(req.params)
152153
if res.string in ["", "{}"]:
153-
return #Notification (see wrapRpc). The client doesnt expect a response
154+
return #Notification (see wrapRpc). The client doesnt expect a response
154155
var json = newJObject()
155156
json["jsonrpc"] = %*"2.0"
156157
if req.id.kind == riNumber:
@@ -163,18 +164,23 @@ proc runRpc(ls: LanguageServer, req: RequestRx, rpc: RpcProc): Future[void] {.as
163164
error "[RunRPC] ", msg = ex.msg, req = req.`method`
164165
writeStackTrace(ex = ex)
165166

166-
proc processMessage(ls: LanguageServer, message: string) {.raises:[].} =
167+
proc processMessage(ls: LanguageServer, message: string) {.raises: [].} =
167168
try:
168-
let contentJson = parseJson(message) #OPT oportunity reuse the same JSON already parsed
169+
let contentJson = parseJson(message)
170+
#OPT oportunity reuse the same JSON already parsed
169171
let isReq = "method" in contentJson
170172
if isReq:
171173
debug "[Processsing Message]", request = contentJson["method"]
172174
var fut = Future[JsonString]()
173175
var req = JrpcSys.decode(message, RequestRx)
174176
if req.params.kind == rpNamed and req.id.kind == riNumber:
175177
#Some requests have no id but for others we need to pass the id to the wrapRpc as the id information is lost in the rpc proc
176-
req.params.named.add ParamDescNamed(name: "idRequest", value: JsonString($(%req.id.num)))
177-
req.params.named.add ParamDescNamed(name: "method", value: JsonString($(contentJson["method"])))
178+
req.params.named.add ParamDescNamed(
179+
name: "idRequest", value: JsonString($(%req.id.num))
180+
)
181+
req.params.named.add ParamDescNamed(
182+
name: "method", value: JsonString($(contentJson["method"]))
183+
)
178184
let rpc = ls.srv.router.procs.getOrDefault(req.meth.get)
179185
if rpc.isNil:
180186
error "[Processsing Message] rpc method not found: ", msg = req.meth.get
@@ -184,15 +190,15 @@ proc processMessage(ls: LanguageServer, message: string) {.raises:[].} =
184190
let response = JrpcSys.decode(message, LspClientResponse)
185191
let id = response.id
186192
if id notin ls.responseMap:
187-
error "Id not found in responseMap", id = id #TODO we should store the call name we are trying to responde to here
193+
error "Id not found in responseMap", id = id
194+
#TODO we should store the call name we are trying to responde to here
188195
if response.result == nil:
189196
ls.responseMap[id].complete(newJObject())
190197
ls.responseMap.del id
191198
else:
192199
let r = response.result
193200
ls.responseMap[id].complete(r)
194201
ls.responseMap.del id
195-
196202
except JsonParsingError as ex:
197203
error "[Processsing Message] Error parsing message", message = message
198204
writeStackTrace(ex)
@@ -202,8 +208,8 @@ proc processMessage(ls: LanguageServer, message: string) {.raises:[].} =
202208

203209
proc initActions*(ls: LanguageServer) =
204210
let onExit: OnExitCallback = proc() {.async.} =
205-
case ls.transportMode:
206-
of stdio:
211+
case ls.transportMode
212+
of stdio:
207213
ls.outStream.close()
208214
freeShared(ls.stdinContext)
209215
of socket:
@@ -216,10 +222,10 @@ proc initActions*(ls: LanguageServer) =
216222
json["params"] = params
217223

218224
let notifyAction: NotifyAction = proc(name: string, params: JsonNode) =
219-
genJsonAction()
220-
ls.writeOutput(json)
225+
genJsonAction()
226+
ls.writeOutput(json)
221227

222-
let callAction: CallAction = proc(name: string, params: JsonNode): Future[JsonNode] =
228+
let callAction: CallAction = proc(name: string, params: JsonNode): Future[JsonNode] =
223229
let id = $genOid()
224230
genJsonAction()
225231
json["id"] = %*id
@@ -232,7 +238,6 @@ proc initActions*(ls: LanguageServer) =
232238
ls.notify = notifyAction
233239
ls.onExit = onExit
234240
235-
236241
#start and loop functions belows are the only difference between transports
237242
proc startStdioLoop*(ls: LanguageServer): Future[void] {.async.} =
238243
while true:
@@ -242,14 +247,14 @@ proc startStdioLoop*(ls: LanguageServer): Future[void] {.async.} =
242247
await ls.stdinContext.onMainReadSignal.fire()
243248
if msg == "":
244249
error "Client discconected"
245-
break
250+
break
246251
ls.processMessage(msg)
247252

248253
proc startStdioServer*(ls: LanguageServer) =
249254
#Holds the responses from the client done via the callAction. Likely this is only needed for stdio
250255
debug "Starting stdio server"
251256
ls.srv = newRpcSocketServer()
252-
ls.initActions()
257+
ls.initActions()
253258
ls.outStream = newFileStream(stdout)
254259
var stdinThread {.global.}: Thread[ptr ReadStdinContext]
255260
ls.stdinContext = createShared(ReadStdinContext)
@@ -258,7 +263,9 @@ proc startStdioServer*(ls: LanguageServer) =
258263
createThread(stdinThread, readStdin, ls.stdinContext)
259264
asyncSpawn ls.startStdioLoop()
260265

261-
proc processClientLoop*(ls: LanguageServer, server: StreamServer, transport: StreamTransport) {.async: (raises: []), gcsafe.} =
266+
proc processClientLoop*(
267+
ls: LanguageServer, server: StreamServer, transport: StreamTransport
268+
) {.async: (raises: []), gcsafe.} =
262269
ls.socketTransport = transport
263270
while true:
264271
let msg = await processContentLength(transport)
@@ -270,8 +277,7 @@ proc processClientLoop*(ls: LanguageServer, server: StreamServer, transport: Str
270277
ls.processMessage(msg)
271278

272279
proc startSocketServer*(ls: LanguageServer, port: Port) =
273-
ls.srv = newRpcSocketServer(partial(processClientLoop, ls))
274-
ls.initActions()
275-
ls.srv.addStreamServer("localhost", port)
276-
ls.srv.start
277-
280+
ls.srv = newRpcSocketServer(partial(processClientLoop, ls))
281+
ls.initActions()
282+
ls.srv.addStreamServer("localhost", port)
283+
ls.srv.start

0 commit comments

Comments
 (0)