summaryrefslogtreecommitdiff
path: root/lsp.c
blob: 830f90d23da2684e3c2ad6152105742fb40706f2 (plain)
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
// print server-to-client communication
#define LSP_SHOW_S2C 0
// print client-to-server communication
#define LSP_SHOW_C2S 0

static void lsp_request_free(LSPRequest *r);
static void lsp_response_free(LSPResponse *r);

#define lsp_set_error(lsp, ...) do {\
		SDL_LockMutex(lsp->error_mutex);\
		strbuf_printf(lsp->error, __VA_ARGS__);\
		SDL_UnlockMutex(lsp->error_mutex);\
	} while (0)
#include "lsp-json.c"
#include "lsp-write.c"
#include "lsp-parse.c"

bool lsp_get_error(LSP *lsp, char *error, size_t error_size, bool clear) {
	bool has_err = false;
	SDL_LockMutex(lsp->error_mutex);
	has_err = *lsp->error != '\0';
	if (error_size)
		str_cpy(error, error_size, lsp->error);
	if (clear)
		*lsp->error = '\0';
	SDL_UnlockMutex(lsp->error_mutex);
	return has_err;
}


static void lsp_document_change_event_free(LSPDocumentChangeEvent *event) {
	free(event->text);
}

static void lsp_request_free(LSPRequest *r) {
	free(r->id_string);
	switch (r->type) {
	case LSP_REQUEST_NONE:
	case LSP_REQUEST_INITIALIZE:
	case LSP_REQUEST_INITIALIZED:
	case LSP_REQUEST_SHUTDOWN:
	case LSP_REQUEST_EXIT:
	case LSP_REQUEST_COMPLETION:
	case LSP_REQUEST_SIGNATURE_HELP:
	case LSP_REQUEST_HOVER:
	case LSP_REQUEST_DEFINITION:
	case LSP_REQUEST_DID_CLOSE:
	case LSP_REQUEST_WORKSPACE_FOLDERS:
	case LSP_REQUEST_JDTLS_CONFIGURATION:
		break;
	case LSP_REQUEST_DID_OPEN: {
		LSPRequestDidOpen *open = &r->data.open;
		free(open->file_contents);
		} break;
	case LSP_REQUEST_SHOW_MESSAGE:
	case LSP_REQUEST_LOG_MESSAGE:
		free(r->data.message.message);
		break;
	case LSP_REQUEST_DID_CHANGE: {
		LSPRequestDidChange *c = &r->data.change;
		arr_foreach_ptr(c->changes, LSPDocumentChangeEvent, event)
			lsp_document_change_event_free(event);
		arr_free(c->changes);
		} break;
	case LSP_REQUEST_DID_CHANGE_WORKSPACE_FOLDERS: {
		LSPRequestDidChangeWorkspaceFolders *w = &r->data.change_workspace_folders;
		arr_free(w->added);
		arr_free(w->removed);
		} break;
	}
	memset(r, 0, sizeof *r);
}

static void lsp_response_free(LSPResponse *r) {
	arr_free(r->string_data);
	switch (r->request.type) {
	case LSP_REQUEST_COMPLETION:
		arr_free(r->data.completion.items);
		break;
	case LSP_REQUEST_SIGNATURE_HELP:
		arr_free(r->data.signature_help.signatures);
		break;
	case LSP_REQUEST_DEFINITION:
		arr_free(r->data.definition.locations);
		break;
	default:
		break;
	}
	lsp_request_free(&r->request);
	memset(r, 0, sizeof *r);
}

void lsp_message_free(LSPMessage *message) {
	switch (message->type) {
	case LSP_REQUEST:
		lsp_request_free(&message->u.request);
		break;
	case LSP_RESPONSE:
		lsp_response_free(&message->u.response);
		break;
	}
	memset(message, 0, sizeof *message);
}


// figure out if data begins with a complete LSP response.
static bool has_response(const char *data, size_t data_len, u64 *p_offset, u64 *p_size) {
	const char *content_length = strstr(data, "Content-Length");
	if (!content_length) return false;
	const char *p = content_length + strlen("Content-Length");
	if (!p[0] || !p[1] || !p[2]) return false;
	p += 2;
	size_t size = (size_t)atoll(p);
	*p_size = size;
	const char *header_end = strstr(content_length, "\r\n\r\n");
	if (!header_end) return false;
	header_end += 4;
	u64 offset = (u64)(header_end - data);
	*p_offset = offset;
	return offset + size <= data_len;
}

static bool lsp_supports_request(LSP *lsp, const LSPRequest *request) {
	LSPCapabilities *cap = &lsp->capabilities;
	switch (request->type) {
	case LSP_REQUEST_NONE:
	// return false for server-to-client requests since we should never send them
	case LSP_REQUEST_SHOW_MESSAGE:
	case LSP_REQUEST_LOG_MESSAGE:
	case LSP_REQUEST_WORKSPACE_FOLDERS:
		return false;
	case LSP_REQUEST_INITIALIZE:
	case LSP_REQUEST_INITIALIZED:
	case LSP_REQUEST_DID_OPEN:
	case LSP_REQUEST_DID_CLOSE:
	case LSP_REQUEST_DID_CHANGE:
	case LSP_REQUEST_SHUTDOWN:
	case LSP_REQUEST_EXIT:
		return true;
	case LSP_REQUEST_JDTLS_CONFIGURATION:
		// @TODO: check if this is actually jdtls
		return lsp->language == LANG_JAVA;
	case LSP_REQUEST_COMPLETION:
		return cap->completion_support;
	case LSP_REQUEST_SIGNATURE_HELP:
		return cap->signature_help_support;
	case LSP_REQUEST_DID_CHANGE_WORKSPACE_FOLDERS:
		return cap->workspace_folders_support;
	case LSP_REQUEST_HOVER:
		return cap->hover_support;
	case LSP_REQUEST_DEFINITION:
		return cap->definition_support;
	}
	assert(0);
	return false;
}

void lsp_send_message(LSP *lsp, LSPMessage *message) {
	SDL_LockMutex(lsp->messages_mutex);
	arr_add(lsp->messages_client2server, *message);
	SDL_UnlockMutex(lsp->messages_mutex);
}

bool lsp_send_request(LSP *lsp, LSPRequest *request) {
	if (!lsp_supports_request(lsp, request)) {
		lsp_request_free(request);
		return false;
	}
	LSPMessage message = {.type = LSP_REQUEST};
	message.u.request = *request;
	lsp_send_message(lsp, &message);
	return true;
}

void lsp_send_response(LSP *lsp, LSPResponse *response) {
	LSPMessage message = {.type = LSP_RESPONSE};
	message.u.response = *response;
	lsp_send_message(lsp, &message);
}

const char *lsp_response_string(const LSPResponse *response, LSPString string) {
	assert(string.offset < arr_len(response->string_data));
	return &response->string_data[string.offset];
}

// receive responses/requests/notifications from LSP, up to max_size bytes.
static void lsp_receive(LSP *lsp, size_t max_size) {

	{
		// read stderr. if all goes well, we shouldn't get anything over stderr.
		char stderr_buf[1024] = {0};
		for (size_t i = 0; i < (max_size + sizeof stderr_buf) / sizeof stderr_buf; ++i) {
			ssize_t nstderr = process_read_stderr(&lsp->process, stderr_buf, sizeof stderr_buf - 1);
			if (nstderr > 0) {
				// uh oh
				stderr_buf[nstderr] = '\0';
				eprint("%s%s%s%s", term_bold(stderr), term_yellow(stderr), stderr_buf, term_clear(stderr));
			} else {
				break;
			}
		}
	}

	size_t received_so_far = arr_len(lsp->received_data);
	arr_reserve(lsp->received_data, received_so_far + max_size + 1);
	long long bytes_read = process_read(&lsp->process, lsp->received_data + received_so_far, max_size);
	if (bytes_read <= 0) {
		// no data
		return;
	}
	received_so_far += (size_t)bytes_read;
	// kind of a hack. this is needed because arr_set_len zeroes the data.
	arr_hdr_(lsp->received_data)->len = (u32)received_so_far;
	lsp->received_data[received_so_far] = '\0';// null terminate
	#if LSP_SHOW_S2C
	printf("%s%s%s\n",term_italics(stdout),lsp->received_data,term_clear(stdout));
	#endif
	
	u64 response_offset=0, response_size=0;
	while (has_response(lsp->received_data, received_so_far, &response_offset, &response_size)) {
		if (response_offset + response_size > arr_len(lsp->received_data)) {
			// we haven't received this whole response yet.
			break;
		}
		
		char *copy = strn_dup(lsp->received_data + response_offset, response_size);
		JSON json = {0};
		if (json_parse(&json, copy)) {
			assert(json.text == copy);
			json.is_text_copied = true;
			process_message(lsp, &json);
		} else {
			lsp_set_error(lsp, "couldn't parse response JSON: %s", json.error);
			json_free(&json);
		}
		size_t leftover_data_len = arr_len(lsp->received_data) - (response_offset + response_size);
		
		//printf("arr_cap = %u response_offset = %u, response_size = %zu, leftover len = %u\n",
		//	arr_hdr_(lsp->received_data)->cap,
		//	response_offset, response_size, leftover_data_len);
		memmove(lsp->received_data, lsp->received_data + response_offset + response_size,
			leftover_data_len);
		arr_set_len(lsp->received_data, leftover_data_len);
		arr_reserve(lsp->received_data, leftover_data_len + 1);
		lsp->received_data[leftover_data_len] = '\0';
	}
}

// send requests.
static bool lsp_send(LSP *lsp) {
	if (!lsp->initialized) {
		// don't send anything before the server is initialized.
		return false;
	}
	
	LSPMessage *messages = NULL;
	SDL_LockMutex(lsp->messages_mutex);
	size_t n_messages = arr_len(lsp->messages_client2server);
	messages = calloc(n_messages, sizeof *messages);
	memcpy(messages, lsp->messages_client2server, n_messages * sizeof *messages);
	
	#if __GNUC__ && !__clang__
	#pragma GCC diagnostic push
	// i don't know why GCC is giving me this. some compiler bug.
	#pragma GCC diagnostic ignored "-Wfree-nonheap-object"
	#endif
	arr_clear(lsp->messages_client2server);
	#if __GNUC__ && !__clang__
	#pragma GCC diagnostic pop
	#endif
	
	SDL_UnlockMutex(lsp->messages_mutex);

	bool quit = false;
	for (size_t i = 0; i < n_messages; ++i) {
		LSPMessage *m = &messages[i];
		if (quit) {
			lsp_message_free(m);
		} else {
			write_message(lsp, m);
		}
		
		if (SDL_SemTryWait(lsp->quit_sem) == 0) {
			quit = true;
		}
	}

	free(messages);
	return quit;
}


// Do any necessary communication with the LSP.
// This writes requests and reads (and parses) responses.
static int lsp_communication_thread(void *data) {
	LSP *lsp = data;
	while (1) {
		bool quit = lsp_send(lsp);
		if (quit) break;
		
		lsp_receive(lsp, (size_t)10<<20);
		if (SDL_SemWaitTimeout(lsp->quit_sem, 5) == 0)
			break;	
	}
	
	if (lsp->initialized) {
		LSPRequest shutdown = {
			.type = LSP_REQUEST_SHUTDOWN,
			.data = {{0}}
		};
		LSPRequest exit = {
			.type = LSP_REQUEST_EXIT,
			.data = {{0}}
		};
		write_request(lsp, &shutdown);
		// i give you ONE MILLISECOND to send your fucking shutdown response
		time_sleep_ms(1);
		write_request(lsp, &exit);
		// i give you ONE MILLISECOND to terminate
		// I WILL KILL YOU IF IT TAKES ANY LONGER
		time_sleep_ms(1);
		
		#if 0
		char buf[1024]={0};
		long long n = process_read(&lsp->process, buf, sizeof buf);
		if (n>0) {
			buf[n]=0;
			printf("%s\n",buf);
		}
		n = process_read_stderr(&lsp->process, buf, sizeof buf);
		if (n>0) {
			buf[n]=0;
			printf("\x1b[1m%s\x1b[0m\n",buf);
		}
		#endif
	}
	return 0;
}

u32 lsp_document_id(LSP *lsp, const char *path) {
	SDL_LockMutex(lsp->document_mutex);
		u32 *value = str_hash_table_get(&lsp->document_ids, path);
		if (!value) {
			u32 id = arr_len(lsp->document_data);
			value = str_hash_table_insert(&lsp->document_ids, path);
			*value = id;
			LSPDocumentData *data = arr_addp(lsp->document_data);
			data->path = str_dup(path);
		}
		u32 id = *value;
	SDL_UnlockMutex(lsp->document_mutex);
	return id;
}

const char *lsp_document_path(LSP *lsp, LSPDocumentID document) {
	SDL_LockMutex(lsp->document_mutex);
		if (document >= arr_len(lsp->document_data)) {
			assert(0);
			return "";
		}
		const char *path = lsp->document_data[document].path;
	SDL_UnlockMutex(lsp->document_mutex);
	return path;
}

LSP *lsp_create(const char *root_dir, Language language, const char *analyzer_command) {
	LSP *lsp = calloc(1, sizeof *lsp);
	if (!lsp) return NULL;
	
	static _Atomic LSPID curr_id = 1;
	lsp->id = curr_id++;
	
	#if DEBUG
		printf("Starting up LSP %p `%s` for language %s in %s\n",
			(void *)lsp, analyzer_command, language_to_str(language), root_dir);
	#endif
	
	str_hash_table_create(&lsp->document_ids, sizeof(u32));
	lsp->language = language;
	lsp->quit_sem = SDL_CreateSemaphore(0);	
	lsp->error_mutex = SDL_CreateMutex();
	lsp->messages_mutex = SDL_CreateMutex();
	arr_add(lsp->workspace_folders, lsp_document_id(lsp, root_dir));
	lsp->workspace_folders_mutex = SDL_CreateMutex();
	
	ProcessSettings settings = {
		.stdin_blocking = true,
		.stdout_blocking = false,
		.stderr_blocking = false,
		.separate_stderr = true,
		.working_directory = root_dir,
	};
	process_run_ex(&lsp->process, analyzer_command, &settings);
	LSPRequest initialize = {
		.type = LSP_REQUEST_INITIALIZE
	};
	// immediately send the request rather than queueing it.
	// this is a small request, so it shouldn't be a problem.
	write_request(lsp, &initialize);
	lsp->communication_thread = SDL_CreateThread(lsp_communication_thread, "LSP communicate", lsp);
	return lsp;
}

bool lsp_try_add_root_dir(LSP *lsp, const char *new_root_dir) {
	assert(lsp->initialized);

	bool got_it = false;
	SDL_LockMutex(lsp->workspace_folders_mutex);
		arr_foreach_ptr(lsp->workspace_folders, LSPDocumentID, folder) {
			if (str_has_path_prefix(new_root_dir, lsp_document_path(lsp, *folder))) {
				got_it = true;
				break;
			}
		}
	SDL_UnlockMutex(lsp->workspace_folders_mutex);
	if (got_it) return true;
	
	if (!lsp->capabilities.workspace_folders_support) {
		return false;
	}
	
	// send workspace/didChangeWorkspaceFolders notification
	LSPRequest req = {.type = LSP_REQUEST_DID_CHANGE_WORKSPACE_FOLDERS};
	LSPRequestDidChangeWorkspaceFolders *w = &req.data.change_workspace_folders;
	LSPDocumentID document_id = lsp_document_id(lsp, new_root_dir);
	arr_add(w->added, document_id);
	lsp_send_request(lsp, &req);
	// *technically* this is incorrect because if the server *just now sent* a
	// workspace/workspaceFolders request, we'd give it back inconsistent information.
	// i don't care.
	SDL_LockMutex(lsp->workspace_folders_mutex);
		arr_add(lsp->workspace_folders, document_id);
	SDL_UnlockMutex(lsp->workspace_folders_mutex);
	return true;
}

bool lsp_next_message(LSP *lsp, LSPMessage *message) {
	bool any = false;
	SDL_LockMutex(lsp->messages_mutex);
	if (arr_len(lsp->messages_server2client)) {
		*message = lsp->messages_server2client[0];
		arr_remove(lsp->messages_server2client, 0);
		any = true;
	}
	SDL_UnlockMutex(lsp->messages_mutex);
	return any;
}

void lsp_free(LSP *lsp) {
	SDL_SemPost(lsp->quit_sem);
	SDL_WaitThread(lsp->communication_thread, NULL);
	SDL_DestroyMutex(lsp->messages_mutex);
	SDL_DestroyMutex(lsp->workspace_folders_mutex);
	SDL_DestroyMutex(lsp->error_mutex);
	SDL_DestroySemaphore(lsp->quit_sem);
	process_kill(&lsp->process);
	
	arr_free(lsp->received_data);
	
	str_hash_table_clear(&lsp->document_ids);
	for (size_t i = 0; i < arr_len(lsp->document_data); ++i)
		free(lsp->document_data[i].path);
	arr_free(lsp->document_data);
	
	arr_foreach_ptr(lsp->messages_server2client, LSPMessage, message)
		lsp_message_free(message);
	arr_free(lsp->messages_server2client);
	
	arr_foreach_ptr(lsp->messages_client2server, LSPMessage, message)
		lsp_message_free(message);
	arr_free(lsp->messages_client2server);
	
	arr_foreach_ptr(lsp->requests_sent, LSPRequest, r)
		lsp_request_free(r);
	arr_free(lsp->requests_sent);
	
	arr_free(lsp->workspace_folders);
	
	arr_free(lsp->completion_trigger_chars);
	arr_free(lsp->signature_help_trigger_chars);
	arr_free(lsp->signature_help_retrigger_chars);
	memset(lsp, 0, sizeof *lsp);
	free(lsp);
}

void lsp_document_changed(LSP *lsp, const char *document, LSPDocumentChangeEvent change) {
	// @TODO(optimization, eventually): batch changes (using the contentChanges array)
	LSPRequest request = {.type = LSP_REQUEST_DID_CHANGE};
	LSPRequestDidChange *c = &request.data.change;
	c->document = lsp_document_id(lsp, document);
	arr_add(c->changes, change);
	lsp_send_request(lsp, &request);
}

#if 0
SymbolKind lsp_symbol_kind_to_ted(LSPSymbolKind kind) {
	switch (kind) {
	case LSP_SYMBOL_OTHER:
	case LSP_SYMBOL_FILE:
	case LSP_SYMBOL_MODULE:
	case LSB_SYMBOL_NAMESPACE:
	case LSP_SYMBOL_PACKAGE:
		return SYMBOL_OTHER;
	
	case LSP_SYMBOL_CLASS:
	case LSP_SYMBOL_TYPEPARAMETER:
	case LSP_SYMBOL_ENUM:
	case LSP_SYMBOL_INTERFACE:
	case LSP_SYMBOL_STRUCT:
	case LSP_SYMBOL_EVENT: // i have no clue what this is. let's say it's a type.
		return SYMBOL_TYPE;
	
	case LSP_SYMBOL_PROPERTY:
	case LSP_SYMBOL_FIELD:
	case LSP_SYMBOL_KEY:
		return SYMBOL_FIELD;
	
	case LSP_SYMBOL_CONSTRUCTOR:
	case LSP_SYMBOL_FUNCTION:
	case LSP_SYMBOL_OPERATOR:
	case LSP_SYMBOL_METHOD:
		return SYMBOL_FUNCTION;
	
	case LSP_SYMBOL_VARIABLE:
		return SYMBOL_VARIABLE;
	
	case LSP_SYMBOL_CONSTANT:
	case LSP_SYMBOL_STRING:
	case LSP_SYMBOL_NUMBER:
	case LSP_SYMBOL_BOOLEAN:
	case LSP_SYMBOL_ARRAY:
	case LSP_SYMBOL_OBJECT:
	case LSP_SYMBOL_ENUMMEMBER:
	case LSP_SYMBOL_NULL:
		return SYMBOL_CONSTANT;
	}
	
	return SYMBOL_OTHER;
}
#endif

bool lsp_position_eq(LSPPosition a, LSPPosition b) {
	return a.line == b.line && a.character == b.character;
}

bool lsp_document_position_eq(LSPDocumentPosition a, LSPDocumentPosition b) {
	return a.document == b.document && lsp_position_eq(a.pos, b.pos);
}


LSPDocumentPosition lsp_location_start_position(LSPLocation location) {
	return (LSPDocumentPosition) {
		.document = location.document,
		.pos = location.range.start
	};
}

LSPDocumentPosition lsp_location_end_position(LSPLocation location) {
	return (LSPDocumentPosition) {
		.document = location.document,
		.pos = location.range.end
	};
}