test_lsp.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. #ifndef TEST_LSP_H
  31. #define TEST_LSP_H
  32. #ifdef TOOLS_ENABLED
  33. #include "tests/test_macros.h"
  34. #include "../language_server/gdscript_extend_parser.h"
  35. #include "../language_server/gdscript_language_protocol.h"
  36. #include "../language_server/gdscript_workspace.h"
  37. #include "../language_server/godot_lsp.h"
  38. #include "core/io/dir_access.h"
  39. #include "core/io/file_access_pack.h"
  40. #include "core/os/os.h"
  41. #include "editor/editor_help.h"
  42. #include "editor/editor_node.h"
  43. #include "modules/gdscript/gdscript_analyzer.h"
  44. #include "modules/regex/regex.h"
  45. #include "thirdparty/doctest/doctest.h"
  46. template <>
  47. struct doctest::StringMaker<lsp::Position> {
  48. static doctest::String convert(const lsp::Position &p_val) {
  49. return p_val.to_string().utf8().get_data();
  50. }
  51. };
  52. template <>
  53. struct doctest::StringMaker<lsp::Range> {
  54. static doctest::String convert(const lsp::Range &p_val) {
  55. return p_val.to_string().utf8().get_data();
  56. }
  57. };
  58. template <>
  59. struct doctest::StringMaker<GodotPosition> {
  60. static doctest::String convert(const GodotPosition &p_val) {
  61. return p_val.to_string().utf8().get_data();
  62. }
  63. };
  64. namespace GDScriptTests {
  65. // LSP GDScript test scripts are located inside project of other GDScript tests:
  66. // Cannot reset `ProjectSettings` (singleton) -> Cannot load another workspace and resources in there.
  67. // -> Reuse GDScript test project. LSP specific scripts are then placed inside `lsp` folder.
  68. // Access via `res://lsp/my_script.gd`.
  69. const String root = "modules/gdscript/tests/scripts/";
  70. /*
  71. * After use:
  72. * * `memdelete` returned `GDScriptLanguageProtocol`.
  73. * * Call `GDScriptTests::::finish_language`.
  74. */
  75. GDScriptLanguageProtocol *initialize(const String &p_root) {
  76. Error err = OK;
  77. Ref<DirAccess> dir(DirAccess::open(p_root, &err));
  78. REQUIRE_MESSAGE(err == OK, "Could not open specified root directory");
  79. String absolute_root = dir->get_current_dir();
  80. init_language(absolute_root);
  81. GDScriptLanguageProtocol *proto = memnew(GDScriptLanguageProtocol);
  82. Ref<GDScriptWorkspace> workspace = GDScriptLanguageProtocol::get_singleton()->get_workspace();
  83. workspace->root = absolute_root;
  84. // On windows: `C:/...` -> `C%3A/...`.
  85. workspace->root_uri = "file:///" + absolute_root.lstrip("/").replace_first(":", "%3A");
  86. return proto;
  87. }
  88. lsp::Position pos(const int p_line, const int p_character) {
  89. lsp::Position p;
  90. p.line = p_line;
  91. p.character = p_character;
  92. return p;
  93. }
  94. lsp::Range range(const lsp::Position p_start, const lsp::Position p_end) {
  95. lsp::Range r;
  96. r.start = p_start;
  97. r.end = p_end;
  98. return r;
  99. }
  100. lsp::TextDocumentPositionParams pos_in(const lsp::DocumentUri &p_uri, const lsp::Position p_pos) {
  101. lsp::TextDocumentPositionParams params;
  102. params.textDocument.uri = p_uri;
  103. params.position = p_pos;
  104. return params;
  105. }
  106. 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) {
  107. Ref<GDScriptWorkspace> workspace = GDScriptLanguageProtocol::get_singleton()->get_workspace();
  108. lsp::TextDocumentPositionParams params = pos_in(p_uri, p_pos);
  109. const lsp::DocumentSymbol *symbol = workspace->resolve_symbol(params);
  110. CHECK(symbol);
  111. if (symbol) {
  112. CHECK_EQ(symbol->uri, p_expected_uri);
  113. CHECK_EQ(symbol->name, p_expected_name);
  114. CHECK_EQ(symbol->selectionRange, p_expected_range);
  115. }
  116. return symbol;
  117. }
  118. struct InlineTestData {
  119. lsp::Range range;
  120. String text;
  121. String name;
  122. String ref;
  123. static bool try_parse(const Vector<String> &p_lines, const int p_line_number, InlineTestData &r_data) {
  124. String line = p_lines[p_line_number];
  125. RegEx regex = RegEx("^\\t*#[ |]*(?<range>(?<left><)?\\^+)(\\s+(?<name>(?!->)\\S+))?(\\s+->\\s+(?<ref>\\S+))?");
  126. Ref<RegExMatch> match = regex.search(line);
  127. if (match.is_null()) {
  128. return false;
  129. }
  130. // Find first line without leading comment above current line.
  131. int target_line = p_line_number;
  132. while (target_line >= 0) {
  133. String dedented = p_lines[target_line].lstrip("\t");
  134. if (!dedented.begins_with("#")) {
  135. break;
  136. }
  137. target_line--;
  138. }
  139. if (target_line < 0) {
  140. return false;
  141. }
  142. r_data.range.start.line = r_data.range.end.line = target_line;
  143. String marker = match->get_string("range");
  144. int i = line.find(marker);
  145. REQUIRE(i >= 0);
  146. r_data.range.start.character = i;
  147. if (!match->get_string("left").is_empty()) {
  148. // Include `#` (comment char) in range.
  149. r_data.range.start.character--;
  150. }
  151. r_data.range.end.character = i + marker.length();
  152. String target = p_lines[target_line];
  153. r_data.text = target.substr(r_data.range.start.character, r_data.range.end.character - r_data.range.start.character);
  154. r_data.name = match->get_string("name");
  155. r_data.ref = match->get_string("ref");
  156. return true;
  157. }
  158. };
  159. Vector<InlineTestData> read_tests(const String &p_path) {
  160. Error err;
  161. String source = FileAccess::get_file_as_string(p_path, &err);
  162. REQUIRE_MESSAGE(err == OK, vformat("Cannot read '%s'", p_path));
  163. // Format:
  164. // ```gdscript
  165. // var foo = bar + baz
  166. // # | | | | ^^^ name -> ref
  167. // # | | ^^^ -> ref
  168. // # ^^^ name
  169. //
  170. // func my_func():
  171. // # ^^^^^^^ name
  172. // var value = foo + 42
  173. // # ^^^^^ name
  174. // print(value)
  175. // # ^^^^^ -> ref
  176. // ```
  177. //
  178. // * `^`: Range marker.
  179. // * `name`: Unique name. Can contain any characters except whitespace chars.
  180. // * `ref`: Reference to unique name.
  181. //
  182. // Notes:
  183. // * If range should include first content-char (which is occupied by `#`): use `<` for next marker.
  184. // -> Range expands 1 to left (-> includes `#`).
  185. // * Note: Means: Range cannot be single char directly marked by `#`, but must be at least two chars (marked with `#<`).
  186. // * Comment must start at same ident as line its marked (-> because of tab alignment...).
  187. // * Use spaces to align after `#`! -> for correct alignment
  188. // * Between `#` and `^` can be spaces or `|` (to better visualize what's marked below).
  189. PackedStringArray lines = source.split("\n");
  190. PackedStringArray names;
  191. Vector<InlineTestData> data;
  192. for (int i = 0; i < lines.size(); i++) {
  193. InlineTestData d;
  194. if (InlineTestData::try_parse(lines, i, d)) {
  195. if (!d.name.is_empty()) {
  196. // Safety check: names must be unique.
  197. if (names.has(d.name)) {
  198. FAIL(vformat("Duplicated name '%s' in '%s'. Names must be unique!", d.name, p_path));
  199. }
  200. names.append(d.name);
  201. }
  202. data.append(d);
  203. }
  204. }
  205. return data;
  206. }
  207. void test_resolve_symbol(const String &p_uri, const InlineTestData &p_test_data, const Vector<InlineTestData> &p_all_data) {
  208. if (p_test_data.ref.is_empty()) {
  209. return;
  210. }
  211. 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()) {
  212. const InlineTestData *target = nullptr;
  213. for (int i = 0; i < p_all_data.size(); i++) {
  214. if (p_all_data[i].name == p_test_data.ref) {
  215. target = &p_all_data[i];
  216. break;
  217. }
  218. }
  219. REQUIRE_MESSAGE(target, vformat("No target for ref '%s'", p_test_data.ref));
  220. Ref<GDScriptWorkspace> workspace = GDScriptLanguageProtocol::get_singleton()->get_workspace();
  221. lsp::Position pos = p_test_data.range.start;
  222. SUBCASE("start of identifier") {
  223. pos.character = p_test_data.range.start.character;
  224. test_resolve_symbol_at(p_uri, pos, p_uri, target->text, target->range);
  225. }
  226. SUBCASE("inside identifier") {
  227. pos.character = (p_test_data.range.end.character + p_test_data.range.start.character) / 2;
  228. test_resolve_symbol_at(p_uri, pos, p_uri, target->text, target->range);
  229. }
  230. SUBCASE("end of identifier") {
  231. pos.character = p_test_data.range.end.character;
  232. test_resolve_symbol_at(p_uri, pos, p_uri, target->text, target->range);
  233. }
  234. }
  235. }
  236. Vector<InlineTestData> filter_ref_towards(const Vector<InlineTestData> &p_data, const String &p_name) {
  237. Vector<InlineTestData> res;
  238. for (const InlineTestData &d : p_data) {
  239. if (d.ref == p_name) {
  240. res.append(d);
  241. }
  242. }
  243. return res;
  244. }
  245. void test_resolve_symbols(const String &p_uri, const Vector<InlineTestData> &p_test_data, const Vector<InlineTestData> &p_all_data) {
  246. for (const InlineTestData &d : p_test_data) {
  247. test_resolve_symbol(p_uri, d, p_all_data);
  248. }
  249. }
  250. void assert_no_errors_in(const String &p_path) {
  251. Error err;
  252. String source = FileAccess::get_file_as_string(p_path, &err);
  253. REQUIRE_MESSAGE(err == OK, vformat("Cannot read '%s'", p_path));
  254. GDScriptParser parser;
  255. err = parser.parse(source, p_path, true);
  256. REQUIRE_MESSAGE(err == OK, vformat("Errors while parsing '%s'", p_path));
  257. GDScriptAnalyzer analyzer(&parser);
  258. err = analyzer.analyze();
  259. REQUIRE_MESSAGE(err == OK, vformat("Errors while analyzing '%s'", p_path));
  260. }
  261. inline lsp::Position lsp_pos(int line, int character) {
  262. lsp::Position p;
  263. p.line = line;
  264. p.character = character;
  265. return p;
  266. }
  267. void test_position_roundtrip(lsp::Position p_lsp, GodotPosition p_gd, const PackedStringArray &p_lines) {
  268. GodotPosition actual_gd = GodotPosition::from_lsp(p_lsp, p_lines);
  269. CHECK_EQ(p_gd, actual_gd);
  270. lsp::Position actual_lsp = p_gd.to_lsp(p_lines);
  271. CHECK_EQ(p_lsp, actual_lsp);
  272. }
  273. // Note:
  274. // * Cursor is BETWEEN chars
  275. // * `va|r` -> cursor between `a`&`r`
  276. // * `var`
  277. // ^
  278. // -> Character on `r` -> cursor between `a`&`r`s for tests:
  279. // * Line & Char:
  280. // * LSP: both 0-based
  281. // * Godot: both 1-based
  282. TEST_SUITE("[Modules][GDScript][LSP]") {
  283. TEST_CASE("Can convert positions to and from Godot") {
  284. String code = R"(extends Node
  285. var member := 42
  286. func f():
  287. var value := 42
  288. return value + member)";
  289. PackedStringArray lines = code.split("\n");
  290. SUBCASE("line after end") {
  291. lsp::Position lsp = lsp_pos(7, 0);
  292. GodotPosition gd(8, 1);
  293. test_position_roundtrip(lsp, gd, lines);
  294. }
  295. SUBCASE("first char in first line") {
  296. lsp::Position lsp = lsp_pos(0, 0);
  297. GodotPosition gd(1, 1);
  298. test_position_roundtrip(lsp, gd, lines);
  299. }
  300. SUBCASE("with tabs") {
  301. // On `v` in `value` in `var value := ...`.
  302. lsp::Position lsp = lsp_pos(5, 6);
  303. GodotPosition gd(6, 13);
  304. test_position_roundtrip(lsp, gd, lines);
  305. }
  306. SUBCASE("doesn't fail with column outside of character length") {
  307. lsp::Position lsp = lsp_pos(2, 100);
  308. GodotPosition::from_lsp(lsp, lines);
  309. GodotPosition gd(3, 100);
  310. gd.to_lsp(lines);
  311. }
  312. SUBCASE("doesn't fail with line outside of line length") {
  313. lsp::Position lsp = lsp_pos(200, 100);
  314. GodotPosition::from_lsp(lsp, lines);
  315. GodotPosition gd(300, 100);
  316. gd.to_lsp(lines);
  317. }
  318. SUBCASE("special case: zero column for root class") {
  319. GodotPosition gd(1, 0);
  320. lsp::Position expected = lsp_pos(0, 0);
  321. lsp::Position actual = gd.to_lsp(lines);
  322. CHECK_EQ(actual, expected);
  323. }
  324. SUBCASE("special case: zero line and column for root class") {
  325. GodotPosition gd(0, 0);
  326. lsp::Position expected = lsp_pos(0, 0);
  327. lsp::Position actual = gd.to_lsp(lines);
  328. CHECK_EQ(actual, expected);
  329. }
  330. SUBCASE("special case: negative line for root class") {
  331. GodotPosition gd(-1, 0);
  332. lsp::Position expected = lsp_pos(0, 0);
  333. lsp::Position actual = gd.to_lsp(lines);
  334. CHECK_EQ(actual, expected);
  335. }
  336. SUBCASE("special case: lines.length() + 1 for root class") {
  337. GodotPosition gd(lines.size() + 1, 0);
  338. lsp::Position expected = lsp_pos(lines.size(), 0);
  339. lsp::Position actual = gd.to_lsp(lines);
  340. CHECK_EQ(actual, expected);
  341. }
  342. }
  343. TEST_CASE("[workspace][resolve_symbol]") {
  344. GDScriptLanguageProtocol *proto = initialize(root);
  345. REQUIRE(proto);
  346. Ref<GDScriptWorkspace> workspace = GDScriptLanguageProtocol::get_singleton()->get_workspace();
  347. {
  348. String path = "res://lsp/local_variables.gd";
  349. assert_no_errors_in(path);
  350. String uri = workspace->get_file_uri(path);
  351. Vector<InlineTestData> all_test_data = read_tests(path);
  352. SUBCASE("Can get correct ranges for public variables") {
  353. Vector<InlineTestData> test_data = filter_ref_towards(all_test_data, "member");
  354. test_resolve_symbols(uri, test_data, all_test_data);
  355. }
  356. SUBCASE("Can get correct ranges for local variables") {
  357. Vector<InlineTestData> test_data = filter_ref_towards(all_test_data, "test");
  358. test_resolve_symbols(uri, test_data, all_test_data);
  359. }
  360. SUBCASE("Can get correct ranges for local parameters") {
  361. Vector<InlineTestData> test_data = filter_ref_towards(all_test_data, "arg");
  362. test_resolve_symbols(uri, test_data, all_test_data);
  363. }
  364. }
  365. SUBCASE("Can get correct ranges for indented variables") {
  366. String path = "res://lsp/indentation.gd";
  367. assert_no_errors_in(path);
  368. String uri = workspace->get_file_uri(path);
  369. Vector<InlineTestData> all_test_data = read_tests(path);
  370. test_resolve_symbols(uri, all_test_data, all_test_data);
  371. }
  372. SUBCASE("Can get correct ranges for scopes") {
  373. String path = "res://lsp/scopes.gd";
  374. assert_no_errors_in(path);
  375. String uri = workspace->get_file_uri(path);
  376. Vector<InlineTestData> all_test_data = read_tests(path);
  377. test_resolve_symbols(uri, all_test_data, all_test_data);
  378. }
  379. SUBCASE("Can get correct ranges for lambda") {
  380. String path = "res://lsp/lambdas.gd";
  381. assert_no_errors_in(path);
  382. String uri = workspace->get_file_uri(path);
  383. Vector<InlineTestData> all_test_data = read_tests(path);
  384. test_resolve_symbols(uri, all_test_data, all_test_data);
  385. }
  386. SUBCASE("Can get correct ranges for inner class") {
  387. String path = "res://lsp/class.gd";
  388. assert_no_errors_in(path);
  389. String uri = workspace->get_file_uri(path);
  390. Vector<InlineTestData> all_test_data = read_tests(path);
  391. test_resolve_symbols(uri, all_test_data, all_test_data);
  392. }
  393. SUBCASE("Can get correct ranges for inner class") {
  394. String path = "res://lsp/enums.gd";
  395. assert_no_errors_in(path);
  396. String uri = workspace->get_file_uri(path);
  397. Vector<InlineTestData> all_test_data = read_tests(path);
  398. test_resolve_symbols(uri, all_test_data, all_test_data);
  399. }
  400. SUBCASE("Can get correct ranges for shadowing & shadowed variables") {
  401. String path = "res://lsp/shadowing_initializer.gd";
  402. assert_no_errors_in(path);
  403. String uri = workspace->get_file_uri(path);
  404. Vector<InlineTestData> all_test_data = read_tests(path);
  405. test_resolve_symbols(uri, all_test_data, all_test_data);
  406. }
  407. SUBCASE("Can get correct ranges for properties and getter/setter") {
  408. String path = "res://lsp/properties.gd";
  409. assert_no_errors_in(path);
  410. String uri = workspace->get_file_uri(path);
  411. Vector<InlineTestData> all_test_data = read_tests(path);
  412. test_resolve_symbols(uri, all_test_data, all_test_data);
  413. }
  414. memdelete(proto);
  415. finish_language();
  416. }
  417. TEST_CASE("[workspace][document_symbol]") {
  418. GDScriptLanguageProtocol *proto = initialize(root);
  419. REQUIRE(proto);
  420. SUBCASE("selectionRange of root class must be inside range") {
  421. String path = "res://lsp/first_line_comment.gd";
  422. assert_no_errors_in(path);
  423. GDScriptLanguageProtocol::get_singleton()->get_workspace()->parse_local_script(path);
  424. ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_workspace()->parse_results[path];
  425. REQUIRE(parser);
  426. lsp::DocumentSymbol cls = parser->get_symbols();
  427. 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)));
  428. 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)));
  429. }
  430. memdelete(proto);
  431. finish_language();
  432. }
  433. }
  434. } // namespace GDScriptTests
  435. #endif // TOOLS_ENABLED
  436. #endif // TEST_LSP_H