Skip to content
← Back

src/analysis/command_despatcher.ghul

1
@@IF.dotnet()
2
3
namespace Analysis is
4
use System.Exception
5
use IO.Std
6
7
use Collections.Iterable
8
9
use Pair = Collections.KeyValuePair
10
11
use Ghul.Pipes
12
13
use IoC
14
use Logging
15
use Source
16
use Compiler
17
18
class COMMAND_DESPATCHER(
19
_reader: REQUEST_READER,
20
_writer: IO.TextWriter,
21
_timers: TIMERS,
22
_log: IO.TextWriter,
23
_watchdog: WATCHDOG,
24
_full_compiler: FULL_COMPILER,
25
_want_stats_report: bool,
26
_idle_timeout_seconds: int
27
) is
28
_command_map: Collections.MAP[System.Type,CommandHandler]
29
30
// The request variants that may be answered part-way through a
31
// compile. See serve_pending_queries for what qualifies.
32
_interleavable: Collections.SET[System.Type]
33
34
_last_report_time: System.DateTime
35
36
_listening: bool
37
38
// Guards against re-entering the interleave: a query served from
39
// inside a compile can reach a handler that compiles in turn,
40
// and its file boundaries would otherwise start another round.
41
_serving_pending: bool
42
43
init(..) is
44
_last_report_time = System.DateTime.now
45
_command_map = Collections.MAP[System.Type,CommandHandler]()
46
_interleavable = Collections.SET[System.Type]()
47
48
_reader.start()
49
si
50
51
// The compiler's own version, sourced from the entry assembly's
52
// AssemblyInformationalVersionAttribute (same source as the driver's
53
// startup log line). Exposed in the LISTEN frame so a client can
54
// reject a version older than the minimum it supports; a bad
55
// version-negotiation error is a lot clearer than a mysterious hang.
56
current_compiler_version() -> string? static is
57
let attribute =
58
System.Reflection.Assembly.get_entry_assembly()!
59
.get_custom_attributes(typeof System.Reflection.AssemblyInformationalVersionAttribute, false)
60
|> map(a => cast System.Reflection.AssemblyInformationalVersionAttribute?(a)!)
61
|> first()
62
63
if attribute? then
64
return attribute.informational_version
65
fi
66
67
return null
68
si
69
70
// Register a handler keyed by the request variant type. A deserialized
71
// request routes to its handler by runtime type; the variant's
72
// unqualified class name (e.g. `HOVER`, `FORMAT_RANGE`) labels the
73
// per-command timer in the stats report.
74
add_handler(request_variant: System.Type, command_handler: CommandHandler) is
75
add_handler(request_variant, command_handler, false)
76
si
77
78
// As above, with `can_interleave` marking the variant as one
79
// serve_pending_queries may answer part-way through a compile.
80
add_handler(request_variant: System.Type, command_handler: CommandHandler, can_interleave: bool) is
81
assert !_command_map.contains_key(request_variant) else "replacing command handler for {request_variant.name}"
82
83
_command_map[request_variant] = command_handler
84
85
if can_interleave then
86
_interleavable.add(request_variant)
87
fi
88
si
89
90
// Wait for the next frame the reader thread queued, exiting
91
// instead if none arrives within the idle timeout.
92
//
93
// Idle-exit lives here rather than in WATCHDOG because it is decided
94
// by the absence of work rather than by anything a compile revealed,
95
// and because this is the one place the analyser is provably between
96
// requests: exiting from anywhere else could truncate a response.
97
read_next_frame() -> QueuedFrame is
98
let frame =
99
_reader.take(
100
if _idle_timeout_seconds <= 0 then
101
0
102
else
103
_idle_timeout_seconds * 1000
104
fi
105
)
106
107
if isa QueuedFrame.TIMED_OUT(frame) then
108
exit_idle()
109
fi
110
111
return frame
112
si
113
114
// Announce the exit and go. Distinct from WATCHDOG.recycle, which
115
// asks the client to relaunch immediately: this asks it to wait
116
// until it has something to ask, and the exit status says the same
117
// thing to a client that was not reading at the time.
118
exit_idle() is
119
_log.write_line("ghūl: exiting after {_idle_timeout_seconds}s idle")
120
_log.flush()
121
122
Protocol.JSON_PROTOCOL.write_response(
123
_writer,
124
Protocol.Response.EXIT("idle for {_idle_timeout_seconds}s")
125
)
126
127
Driver.COMPILER_ENVIRONMENT.exit(0)
128
si
129
130
poll() -> bool is
131
if !_listening then
132
let listen_capabilities = Collections.LIST[string]()
133
// The incremental body re-walk is on by default; this
134
// capability tells a client the analyser supports it.
135
listen_capabilities.add("incremental-analysis")
136
137
// Quick fixes are answered by the `code_actions` request
138
// rather than attached to reported diagnostics. A client
139
// that does not see this must not send the request: the
140
// analyser it is talking to would reject the frame, and
141
// read its own fixes out of the diagnostics instead.
142
listen_capabilities.add("code-actions")
143
144
// An edit can be sent as the span that changed rather
145
// than as the file's whole text. A client that does not
146
// see this must not send the request: unknown JSON
147
// members are ignored, so an analyser without the
148
// capability reads a delta as an edit whose source is
149
// empty and blanks the file.
150
listen_capabilities.add("edit-deltas")
151
152
// A query sent while a compile is running is answered
153
// during it rather than after it. Nothing about the wire
154
// changes - a client that ignores this and waits for its
155
// response as before is served exactly as it was - but a
156
// client that pipelines queries against a compile can
157
// know it will get answers rather than a stall.
158
listen_capabilities.add("mid-compile-queries")
159
160
// An edit written while a compile is running cuts that
161
// compile short instead of queueing behind it. A client
162
// that does not see this must hold its edits until the
163
// compile's response arrives: the analyser it is talking
164
// to would run the whole compile computing diagnostics
165
// the edit has already made stale.
166
listen_capabilities.add("compile-abort")
167
168
// Inlay hints can be asked for by range. Unknown JSON
169
// members are ignored, so a range sent to an analyser
170
// without the capability is simply dropped and the answer
171
// comes back whole-file; the capability lets a client
172
// that checks avoid paying transport for hints outside
173
// the viewport it asked about.
174
listen_capabilities.add("inlay-hint-ranges")
175
176
// A client adding references to a running analyser: an
177
// analyser without it fails the request as unknown.
178
listen_capabilities.add("add-references")
179
180
Protocol.JSON_PROTOCOL.write_response(_writer, Protocol.Response.LISTEN(listen_capabilities, current_compiler_version()))
181
182
_listening = true
183
fi
184
185
let frame = read_next_frame()
186
187
if let parse_error: QueuedFrame.PARSE_ERROR = frame then
188
// A frame the analyser couldn't deserialize is a protocol
189
// mismatch, not analyser instability - typically a client
190
// sending a request variant the analyser doesn't know
191
// (older analyser + newer client). Answer with a discrete
192
// error frame so the client can surface it, and keep the
193
// process alive to serve subsequent requests.
194
_log.write_line("ghūl: could not parse request: {parse_error.message}")
195
196
Protocol.JSON_PROTOCOL.write_response(
197
_writer,
198
Protocol.Response.ERROR("parse", parse_error.message, "")
199
)
200
201
_watchdog.on_operation_complete(_writer)
202
203
return true
204
fi
205
206
let queued = cast QueuedFrame.REQUEST?(frame)
207
208
if !queued? then
209
_log.write_line("ghūl: reader is at end")
210
_log.flush()
211
212
return false
213
fi
214
215
let request = queued.request
216
217
despatch(request)
218
219
_watchdog.on_operation_complete(_writer)
220
221
if _want_stats_report then
222
let elapsed_since_last_report = System.DateTime.now.subtract(_last_report_time)
223
224
if elapsed_since_last_report.total_seconds > 60.0D then
225
_last_report_time = System.DateTime.now
226
227
_log.write(_timers)
228
fi
229
fi
230
231
return true
232
si
233
234
// Route one request to its handler and time it. Reached both from
235
// poll and, for the interleavable variants, from
236
// serve_pending_queries.
237
despatch(request: Protocol.Request) is
238
let request_variant = request.get_type()
239
let command_name = request_variant.name
240
241
if !_command_map.contains_key(request_variant) then
242
// Registered variants with no handler are also a protocol
243
// mismatch - the request kind exists on the wire but this
244
// build doesn't route it anywhere. Same treatment as an
245
// unparseable frame: emit an error and keep going.
246
_log.write_line("ghūl: no handler found for command: '{command_name}'")
247
248
Protocol.JSON_PROTOCOL.write_response(
249
_writer,
250
Protocol.Response.ERROR("unknown_command", "no handler registered for request kind {command_name}", command_name)
251
)
252
253
return
254
fi
255
256
let handler = _command_map[request_variant]
257
258
_timers.start(command_name)
259
handler.handle(request, _writer)
260
_timers.finish(command_name)
261
si
262
263
// Whether an edit is waiting on the pipe, superseding whatever is
264
// being computed now. Read at the same per-file boundaries the
265
// queries are served at, by a compile that can abandon its walk.
266
is_superseded() -> bool =>
267
_reader.has_pending(
268
r =>
269
isa Protocol.Request.EDIT(r) \/
270
isa Protocol.Request.EDIT_DELTA(r)
271
)
272
273
// Answer the queries already waiting on the pipe, from the state
274
// the analyser holds right now, and return to what was being done.
275
//
276
// Called at the per-file boundaries of the compile-expressions
277
// walk, and only there. That window is the one place mid-compile
278
// state is as consistent as it is between requests: every file's
279
// declarations, ancestries and types are resolved before the walk
280
// starts, and the scope and namespace stacks are back at their
281
// base between files. Earlier passes of a from-scratch rebuild
282
// are repopulating the symbol table and answer nothing reliably.
283
//
284
// Only the variants registered as interleavable are taken, and
285
// what qualifies is a query that fails safe: one whose answer is
286
// either right or absent. A whole-project query - references,
287
// implementations, rename - would instead answer from a use map
288
// that is still being rebuilt, and an incomplete set of edit
289
// sites reads as a complete one. Those keep waiting.
290
//
291
// Recompiles are suspended for the duration, so a query that
292
// misses answers from current state rather than starting a
293
// second compile inside this one.
294
serve_pending_queries() is
295
if _serving_pending then
296
return
297
fi
298
299
_serving_pending = true
300
301
let symbol_table = IoC.CONTAINER.instance.symbol_table
302
let scope_mark = symbol_table.mark_scope_stack()
303
304
_full_compiler.suspend_recompiles = true
305
306
try
307
while let request = _reader.take_if(r => _interleavable.contains(r.get_type())) do
308
_timers.bump("interleaved-query")
309
310
despatch(request)
311
od
312
finally
313
// A handler that walks a file - completion, signature
314
// help - pushes scopes as it goes, and one that threw
315
// part-way through would otherwise leave them for the
316
// rest of the compile to trip over.
317
symbol_table.release_scope_stack(scope_mark)
318
IoC.CONTAINER.instance.namespaces.pop_all_namespaces()
319
320
_full_compiler.suspend_recompiles = false
321
322
_serving_pending = false
323
yrt
324
si
325
si
326
si