Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/modules/gdscript/tests/test_lsp.h
10278 views
1
/**************************************************************************/
2
/* test_lsp.h */
3
/**************************************************************************/
4
/* This file is part of: */
5
/* GODOT ENGINE */
6
/* https://godotengine.org */
7
/**************************************************************************/
8
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10
/* */
11
/* Permission is hereby granted, free of charge, to any person obtaining */
12
/* a copy of this software and associated documentation files (the */
13
/* "Software"), to deal in the Software without restriction, including */
14
/* without limitation the rights to use, copy, modify, merge, publish, */
15
/* distribute, sublicense, and/or sell copies of the Software, and to */
16
/* permit persons to whom the Software is furnished to do so, subject to */
17
/* the following conditions: */
18
/* */
19
/* The above copyright notice and this permission notice shall be */
20
/* included in all copies or substantial portions of the Software. */
21
/* */
22
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29
/**************************************************************************/
30
31
#pragma once
32
33
#ifdef TOOLS_ENABLED
34
35
#include "modules/modules_enabled.gen.h" // For jsonrpc.
36
37
#ifdef MODULE_JSONRPC_ENABLED
38
39
#include "tests/test_macros.h"
40
41
#include "../language_server/gdscript_extend_parser.h"
42
#include "../language_server/gdscript_language_protocol.h"
43
#include "../language_server/gdscript_workspace.h"
44
#include "../language_server/godot_lsp.h"
45
46
#include "core/io/dir_access.h"
47
#include "core/io/file_access_pack.h"
48
#include "core/os/os.h"
49
#include "editor/doc/editor_help.h"
50
#include "editor/editor_node.h"
51
52
#include "modules/gdscript/gdscript_analyzer.h"
53
#include "modules/regex/regex.h"
54
55
#include "thirdparty/doctest/doctest.h"
56
57
template <>
58
struct doctest::StringMaker<LSP::Position> {
59
static doctest::String convert(const LSP::Position &p_val) {
60
return p_val.to_string().utf8().get_data();
61
}
62
};
63
64
template <>
65
struct doctest::StringMaker<LSP::Range> {
66
static doctest::String convert(const LSP::Range &p_val) {
67
return p_val.to_string().utf8().get_data();
68
}
69
};
70
71
template <>
72
struct doctest::StringMaker<GodotPosition> {
73
static doctest::String convert(const GodotPosition &p_val) {
74
return p_val.to_string().utf8().get_data();
75
}
76
};
77
78
namespace GDScriptTests {
79
80
// LSP GDScript test scripts are located inside project of other GDScript tests:
81
// Cannot reset `ProjectSettings` (singleton) -> Cannot load another workspace and resources in there.
82
// -> Reuse GDScript test project. LSP specific scripts are then placed inside `lsp` folder.
83
// Access via `res://lsp/my_script.gd`.
84
const String root = "modules/gdscript/tests/scripts/";
85
86
/*
87
* After use:
88
* * `memdelete` returned `GDScriptLanguageProtocol`.
89
* * Call `GDScriptTests::::finish_language`.
90
*/
91
GDScriptLanguageProtocol *initialize(const String &p_root) {
92
Error err = OK;
93
Ref<DirAccess> dir(DirAccess::open(p_root, &err));
94
REQUIRE_MESSAGE(err == OK, "Could not open specified root directory");
95
String absolute_root = dir->get_current_dir();
96
init_language(absolute_root);
97
98
GDScriptLanguageProtocol *proto = memnew(GDScriptLanguageProtocol);
99
100
Ref<GDScriptWorkspace> workspace = GDScriptLanguageProtocol::get_singleton()->get_workspace();
101
workspace->root = absolute_root;
102
// On windows: `C:/...` -> `C%3A/...`.
103
workspace->root_uri = "file:///" + absolute_root.lstrip("/").replace_first(":", "%3A");
104
105
return proto;
106
}
107
108
LSP::Position pos(const int p_line, const int p_character) {
109
LSP::Position p;
110
p.line = p_line;
111
p.character = p_character;
112
return p;
113
}
114
115
LSP::Range range(const LSP::Position p_start, const LSP::Position p_end) {
116
LSP::Range r;
117
r.start = p_start;
118
r.end = p_end;
119
return r;
120
}
121
122
LSP::TextDocumentPositionParams pos_in(const LSP::DocumentUri &p_uri, const LSP::Position p_pos) {
123
LSP::TextDocumentPositionParams params;
124
params.textDocument.uri = p_uri;
125
params.position = p_pos;
126
return params;
127
}
128
129
const LSP::DocumentSymbol *test_resolve_symbol_at(const String &p_uri, const LSP::Position p_pos, const String &p_expected_uri, const String &p_expected_name, const LSP::Range &p_expected_range) {
130
Ref<GDScriptWorkspace> workspace = GDScriptLanguageProtocol::get_singleton()->get_workspace();
131
132
LSP::TextDocumentPositionParams params = pos_in(p_uri, p_pos);
133
const LSP::DocumentSymbol *symbol = workspace->resolve_symbol(params);
134
CHECK(symbol);
135
136
if (symbol) {
137
CHECK_EQ(symbol->uri, p_expected_uri);
138
CHECK_EQ(symbol->name, p_expected_name);
139
CHECK_EQ(symbol->selectionRange, p_expected_range);
140
}
141
142
return symbol;
143
}
144
145
struct InlineTestData {
146
LSP::Range range;
147
String text;
148
String name;
149
String ref;
150
151
static bool try_parse(const Vector<String> &p_lines, const int p_line_number, InlineTestData &r_data) {
152
String line = p_lines[p_line_number];
153
154
RegEx regex = RegEx("^\\t*#[ |]*(?<range>(?<left><)?\\^+)(\\s+(?<name>(?!->)\\S+))?(\\s+->\\s+(?<ref>\\S+))?");
155
Ref<RegExMatch> match = regex.search(line);
156
if (match.is_null()) {
157
return false;
158
}
159
160
// Find first line without leading comment above current line.
161
int target_line = p_line_number;
162
while (target_line >= 0) {
163
String dedented = p_lines[target_line].lstrip("\t");
164
if (!dedented.begins_with("#")) {
165
break;
166
}
167
target_line--;
168
}
169
if (target_line < 0) {
170
return false;
171
}
172
r_data.range.start.line = r_data.range.end.line = target_line;
173
174
String marker = match->get_string("range");
175
int i = line.find(marker);
176
REQUIRE(i >= 0);
177
r_data.range.start.character = i;
178
if (!match->get_string("left").is_empty()) {
179
// Include `#` (comment char) in range.
180
r_data.range.start.character--;
181
}
182
r_data.range.end.character = i + marker.length();
183
184
String target = p_lines[target_line];
185
r_data.text = target.substr(r_data.range.start.character, r_data.range.end.character - r_data.range.start.character);
186
187
r_data.name = match->get_string("name");
188
r_data.ref = match->get_string("ref");
189
190
return true;
191
}
192
};
193
194
Vector<InlineTestData> read_tests(const String &p_path) {
195
Error err;
196
String source = FileAccess::get_file_as_string(p_path, &err);
197
REQUIRE_MESSAGE(err == OK, vformat("Cannot read '%s'", p_path));
198
199
// Format:
200
// ```gdscript
201
// var foo = bar + baz
202
// # | | | | ^^^ name -> ref
203
// # | | ^^^ -> ref
204
// # ^^^ name
205
//
206
// func my_func():
207
// # ^^^^^^^ name
208
// var value = foo + 42
209
// # ^^^^^ name
210
// print(value)
211
// # ^^^^^ -> ref
212
// ```
213
//
214
// * `^`: Range marker.
215
// * `name`: Unique name. Can contain any characters except whitespace chars.
216
// * `ref`: Reference to unique name.
217
//
218
// Notes:
219
// * If range should include first content-char (which is occupied by `#`): use `<` for next marker.
220
// -> Range expands 1 to left (-> includes `#`).
221
// * Note: Means: Range cannot be single char directly marked by `#`, but must be at least two chars (marked with `#<`).
222
// * Comment must start at same ident as line its marked (-> because of tab alignment...).
223
// * Use spaces to align after `#`! -> for correct alignment
224
// * Between `#` and `^` can be spaces or `|` (to better visualize what's marked below).
225
PackedStringArray lines = source.split("\n");
226
227
PackedStringArray names;
228
Vector<InlineTestData> data;
229
for (int i = 0; i < lines.size(); i++) {
230
InlineTestData d;
231
if (InlineTestData::try_parse(lines, i, d)) {
232
if (!d.name.is_empty()) {
233
// Safety check: names must be unique.
234
if (names.has(d.name)) {
235
FAIL(vformat("Duplicated name '%s' in '%s'. Names must be unique!", d.name, p_path));
236
}
237
names.append(d.name);
238
}
239
240
data.append(d);
241
}
242
}
243
244
return data;
245
}
246
247
void test_resolve_symbol(const String &p_uri, const InlineTestData &p_test_data, const Vector<InlineTestData> &p_all_data) {
248
if (p_test_data.ref.is_empty()) {
249
return;
250
}
251
252
SUBCASE(vformat("Can resolve symbol '%s' at %s to '%s'", p_test_data.text, p_test_data.range.to_string(), p_test_data.ref).utf8().get_data()) {
253
const InlineTestData *target = nullptr;
254
for (int i = 0; i < p_all_data.size(); i++) {
255
if (p_all_data[i].name == p_test_data.ref) {
256
target = &p_all_data[i];
257
break;
258
}
259
}
260
REQUIRE_MESSAGE(target, vformat("No target for ref '%s'", p_test_data.ref));
261
262
Ref<GDScriptWorkspace> workspace = GDScriptLanguageProtocol::get_singleton()->get_workspace();
263
LSP::Position pos = p_test_data.range.start;
264
265
SUBCASE("start of identifier") {
266
pos.character = p_test_data.range.start.character;
267
test_resolve_symbol_at(p_uri, pos, p_uri, target->text, target->range);
268
}
269
270
SUBCASE("inside identifier") {
271
pos.character = (p_test_data.range.end.character + p_test_data.range.start.character) / 2;
272
test_resolve_symbol_at(p_uri, pos, p_uri, target->text, target->range);
273
}
274
275
SUBCASE("end of identifier") {
276
pos.character = p_test_data.range.end.character;
277
test_resolve_symbol_at(p_uri, pos, p_uri, target->text, target->range);
278
}
279
}
280
}
281
282
Vector<InlineTestData> filter_ref_towards(const Vector<InlineTestData> &p_data, const String &p_name) {
283
Vector<InlineTestData> res;
284
285
for (const InlineTestData &d : p_data) {
286
if (d.ref == p_name) {
287
res.append(d);
288
}
289
}
290
291
return res;
292
}
293
294
void test_resolve_symbols(const String &p_uri, const Vector<InlineTestData> &p_test_data, const Vector<InlineTestData> &p_all_data) {
295
for (const InlineTestData &d : p_test_data) {
296
test_resolve_symbol(p_uri, d, p_all_data);
297
}
298
}
299
300
void assert_no_errors_in(const String &p_path) {
301
Error err;
302
String source = FileAccess::get_file_as_string(p_path, &err);
303
REQUIRE_MESSAGE(err == OK, vformat("Cannot read '%s'", p_path));
304
305
GDScriptParser parser;
306
err = parser.parse(source, p_path, true);
307
REQUIRE_MESSAGE(err == OK, vformat("Errors while parsing '%s'", p_path));
308
309
GDScriptAnalyzer analyzer(&parser);
310
err = analyzer.analyze();
311
REQUIRE_MESSAGE(err == OK, vformat("Errors while analyzing '%s'", p_path));
312
}
313
314
inline LSP::Position lsp_pos(int line, int character) {
315
LSP::Position p;
316
p.line = line;
317
p.character = character;
318
return p;
319
}
320
321
void test_position_roundtrip(LSP::Position p_lsp, GodotPosition p_gd, const PackedStringArray &p_lines) {
322
GodotPosition actual_gd = GodotPosition::from_lsp(p_lsp, p_lines);
323
CHECK_EQ(p_gd, actual_gd);
324
LSP::Position actual_lsp = p_gd.to_lsp(p_lines);
325
CHECK_EQ(p_lsp, actual_lsp);
326
}
327
328
// Note:
329
// * Cursor is BETWEEN chars
330
// * `va|r` -> cursor between `a`&`r`
331
// * `var`
332
// ^
333
// -> Character on `r` -> cursor between `a`&`r`s for tests:
334
// * Line & Char:
335
// * LSP: both 0-based
336
// * Godot: both 1-based
337
TEST_SUITE("[Modules][GDScript][LSP][Editor]") {
338
TEST_CASE("Can convert positions to and from Godot") {
339
String code = R"(extends Node
340
341
var member := 42
342
343
func f():
344
var value := 42
345
return value + member)";
346
PackedStringArray lines = code.split("\n");
347
348
SUBCASE("line after end") {
349
LSP::Position lsp = lsp_pos(7, 0);
350
GodotPosition gd(8, 1);
351
test_position_roundtrip(lsp, gd, lines);
352
}
353
SUBCASE("first char in first line") {
354
LSP::Position lsp = lsp_pos(0, 0);
355
GodotPosition gd(1, 1);
356
test_position_roundtrip(lsp, gd, lines);
357
}
358
359
SUBCASE("with tabs") {
360
// On `v` in `value` in `var value := ...`.
361
LSP::Position lsp = lsp_pos(5, 6);
362
GodotPosition gd(6, 13);
363
test_position_roundtrip(lsp, gd, lines);
364
}
365
366
SUBCASE("doesn't fail with column outside of character length") {
367
LSP::Position lsp = lsp_pos(2, 100);
368
GodotPosition::from_lsp(lsp, lines);
369
370
GodotPosition gd(3, 100);
371
gd.to_lsp(lines);
372
}
373
374
SUBCASE("doesn't fail with line outside of line length") {
375
LSP::Position lsp = lsp_pos(200, 100);
376
GodotPosition::from_lsp(lsp, lines);
377
378
GodotPosition gd(300, 100);
379
gd.to_lsp(lines);
380
}
381
382
SUBCASE("special case: zero column for root class") {
383
GodotPosition gd(1, 0);
384
LSP::Position expected = lsp_pos(0, 0);
385
LSP::Position actual = gd.to_lsp(lines);
386
CHECK_EQ(actual, expected);
387
}
388
SUBCASE("special case: zero line and column for root class") {
389
GodotPosition gd(0, 0);
390
LSP::Position expected = lsp_pos(0, 0);
391
LSP::Position actual = gd.to_lsp(lines);
392
CHECK_EQ(actual, expected);
393
}
394
SUBCASE("special case: negative line for root class") {
395
GodotPosition gd(-1, 0);
396
LSP::Position expected = lsp_pos(0, 0);
397
LSP::Position actual = gd.to_lsp(lines);
398
CHECK_EQ(actual, expected);
399
}
400
SUBCASE("special case: lines.length() + 1 for root class") {
401
GodotPosition gd(lines.size() + 1, 0);
402
LSP::Position expected = lsp_pos(lines.size(), 0);
403
LSP::Position actual = gd.to_lsp(lines);
404
CHECK_EQ(actual, expected);
405
}
406
}
407
TEST_CASE("[workspace][resolve_symbol]") {
408
EditorFileSystem *efs = memnew(EditorFileSystem);
409
GDScriptLanguageProtocol *proto = initialize(root);
410
REQUIRE(proto);
411
Ref<GDScriptWorkspace> workspace = GDScriptLanguageProtocol::get_singleton()->get_workspace();
412
413
{
414
String path = "res://lsp/local_variables.gd";
415
assert_no_errors_in(path);
416
String uri = workspace->get_file_uri(path);
417
Vector<InlineTestData> all_test_data = read_tests(path);
418
SUBCASE("Can get correct ranges for public variables") {
419
Vector<InlineTestData> test_data = filter_ref_towards(all_test_data, "member");
420
test_resolve_symbols(uri, test_data, all_test_data);
421
}
422
SUBCASE("Can get correct ranges for local variables") {
423
Vector<InlineTestData> test_data = filter_ref_towards(all_test_data, "test");
424
test_resolve_symbols(uri, test_data, all_test_data);
425
}
426
SUBCASE("Can get correct ranges for local parameters") {
427
Vector<InlineTestData> test_data = filter_ref_towards(all_test_data, "arg");
428
test_resolve_symbols(uri, test_data, all_test_data);
429
}
430
}
431
432
SUBCASE("Can get correct ranges for indented variables") {
433
String path = "res://lsp/indentation.gd";
434
assert_no_errors_in(path);
435
String uri = workspace->get_file_uri(path);
436
Vector<InlineTestData> all_test_data = read_tests(path);
437
test_resolve_symbols(uri, all_test_data, all_test_data);
438
}
439
440
SUBCASE("Can get correct ranges for scopes") {
441
String path = "res://lsp/scopes.gd";
442
assert_no_errors_in(path);
443
String uri = workspace->get_file_uri(path);
444
Vector<InlineTestData> all_test_data = read_tests(path);
445
test_resolve_symbols(uri, all_test_data, all_test_data);
446
}
447
448
SUBCASE("Can get correct ranges for lambda") {
449
String path = "res://lsp/lambdas.gd";
450
assert_no_errors_in(path);
451
String uri = workspace->get_file_uri(path);
452
Vector<InlineTestData> all_test_data = read_tests(path);
453
test_resolve_symbols(uri, all_test_data, all_test_data);
454
}
455
456
SUBCASE("Can get correct ranges for inner class") {
457
String path = "res://lsp/class.gd";
458
assert_no_errors_in(path);
459
String uri = workspace->get_file_uri(path);
460
Vector<InlineTestData> all_test_data = read_tests(path);
461
test_resolve_symbols(uri, all_test_data, all_test_data);
462
}
463
464
SUBCASE("Can get correct ranges for inner class") {
465
String path = "res://lsp/enums.gd";
466
assert_no_errors_in(path);
467
String uri = workspace->get_file_uri(path);
468
Vector<InlineTestData> all_test_data = read_tests(path);
469
test_resolve_symbols(uri, all_test_data, all_test_data);
470
}
471
472
SUBCASE("Can get correct ranges for shadowing & shadowed variables") {
473
String path = "res://lsp/shadowing_initializer.gd";
474
assert_no_errors_in(path);
475
String uri = workspace->get_file_uri(path);
476
Vector<InlineTestData> all_test_data = read_tests(path);
477
test_resolve_symbols(uri, all_test_data, all_test_data);
478
}
479
480
SUBCASE("Can get correct ranges for properties and getter/setter") {
481
String path = "res://lsp/properties.gd";
482
assert_no_errors_in(path);
483
String uri = workspace->get_file_uri(path);
484
Vector<InlineTestData> all_test_data = read_tests(path);
485
test_resolve_symbols(uri, all_test_data, all_test_data);
486
}
487
488
memdelete(proto);
489
memdelete(efs);
490
finish_language();
491
}
492
TEST_CASE("[workspace][document_symbol]") {
493
EditorFileSystem *efs = memnew(EditorFileSystem);
494
GDScriptLanguageProtocol *proto = initialize(root);
495
REQUIRE(proto);
496
497
SUBCASE("selectionRange of root class must be inside range") {
498
LocalVector<String> paths = {
499
"res://lsp/first_line_comment.gd", // Comment on first line
500
"res://lsp/first_line_class_name.gd", // class_name (and thus selection range) before extends
501
};
502
503
for (const String &path : paths) {
504
assert_no_errors_in(path);
505
GDScriptLanguageProtocol::get_singleton()->get_workspace()->parse_local_script(path);
506
ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_workspace()->parse_results[path];
507
REQUIRE(parser);
508
LSP::DocumentSymbol cls = parser->get_symbols();
509
510
REQUIRE(((cls.range.start.line == cls.selectionRange.start.line && cls.range.start.character <= cls.selectionRange.start.character) || (cls.range.start.line < cls.selectionRange.start.line)));
511
REQUIRE(((cls.range.end.line == cls.selectionRange.end.line && cls.range.end.character >= cls.selectionRange.end.character) || (cls.range.end.line > cls.selectionRange.end.line)));
512
}
513
}
514
515
SUBCASE("Documentation is correctly set") {
516
String path = "res://lsp/doc_comments.gd";
517
assert_no_errors_in(path);
518
GDScriptLanguageProtocol::get_singleton()->get_workspace()->parse_local_script(path);
519
ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_workspace()->parse_results[path];
520
REQUIRE(parser);
521
LSP::DocumentSymbol cls = parser->get_symbols();
522
REQUIRE(cls.documentation.contains("brief"));
523
REQUIRE(cls.documentation.contains("description"));
524
REQUIRE(cls.documentation.contains("t1"));
525
REQUIRE(cls.documentation.contains("t2"));
526
REQUIRE(cls.documentation.contains("t3"));
527
}
528
529
memdelete(proto);
530
memdelete(efs);
531
finish_language();
532
}
533
}
534
535
} // namespace GDScriptTests
536
537
#endif // MODULE_JSONRPC_ENABLED
538
539
#endif // TOOLS_ENABLED
540
541