test_lsp.h 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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. #pragma once
  31. #ifdef TOOLS_ENABLED
  32. #include "modules/modules_enabled.gen.h" // For jsonrpc.
  33. #ifdef MODULE_JSONRPC_ENABLED
  34. #include "tests/test_macros.h"
  35. #include "../language_server/gdscript_extend_parser.h"
  36. #include "../language_server/gdscript_language_protocol.h"
  37. #include "../language_server/gdscript_workspace.h"
  38. #include "../language_server/godot_lsp.h"
  39. #include "core/io/dir_access.h"
  40. #include "core/io/file_access_pack.h"
  41. #include "core/os/os.h"
  42. #include "editor/doc/editor_help.h"
  43. #include "editor/editor_node.h"
  44. #include "modules/gdscript/gdscript_analyzer.h"
  45. #include "modules/regex/regex.h"
  46. #include "thirdparty/doctest/doctest.h"
  47. template <>
  48. struct doctest::StringMaker<LSP::Position> {
  49. static doctest::String convert(const LSP::Position &p_val) {
  50. return p_val.to_string().utf8().get_data();
  51. }
  52. };
  53. template <>
  54. struct doctest::StringMaker<LSP::Range> {
  55. static doctest::String convert(const LSP::Range &p_val) {
  56. return p_val.to_string().utf8().get_data();
  57. }
  58. };
  59. template <>
  60. struct doctest::StringMaker<GodotPosition> {
  61. static doctest::String convert(const GodotPosition &p_val) {
  62. return p_val.to_string().utf8().get_data();
  63. }
  64. };
  65. namespace GDScriptTests {
  66. // LSP GDScript test scripts are located inside project of other GDScript tests:
  67. // Cannot reset `ProjectSettings` (singleton) -> Cannot load another workspace and resources in there.
  68. // -> Reuse GDScript test project. LSP specific scripts are then placed inside `lsp` folder.
  69. // Access via `res://lsp/my_script.gd`.
  70. const String root = "modules/gdscript/tests/scripts/";
  71. /*
  72. * After use:
  73. * * `memdelete` returned `GDScriptLanguageProtocol`.
  74. * * Call `GDScriptTests::::finish_language`.
  75. */
  76. GDScriptLanguageProtocol *initialize(const String &p_root) {
  77. Error err = OK;
  78. Ref<DirAccess> dir(DirAccess::open(p_root, &err));
  79. REQUIRE_MESSAGE(err == OK, "Could not open specified root directory");
  80. String absolute_root = dir->get_current_dir();
  81. init_language(absolute_root);
  82. GDScriptLanguageProtocol *proto = memnew(GDScriptLanguageProtocol);
  83. Ref<GDScriptWorkspace> workspace = GDScriptLanguageProtocol::get_singleton()->get_workspace();
  84. workspace->root = absolute_root;
  85. // On windows: `C:/...` -> `C%3A/...`.
  86. workspace->root_uri = "file:///" + absolute_root.lstrip("/").replace_first(":", "%3A");
  87. return proto;
  88. }
  89. LSP::Position pos(const int p_line, const int p_character) {
  90. LSP::Position p;
  91. p.line = p_line;
  92. p.character = p_character;
  93. return p;
  94. }
  95. LSP::Range range(const LSP::Position p_start, const LSP::Position p_end) {
  96. LSP::Range r;
  97. r.start = p_start;
  98. r.end = p_end;
  99. return r;
  100. }
  101. LSP::TextDocumentPositionParams pos_in(const LSP::DocumentUri &p_uri, const LSP::Position p_pos) {
  102. LSP::TextDocumentPositionParams params;
  103. params.textDocument.uri = p_uri;
  104. params.position = p_pos;
  105. return params;
  106. }
  107. 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) {
  108. Ref<GDScriptWorkspace> workspace = GDScriptLanguageProtocol::get_singleton()->get_workspace();
  109. LSP::TextDocumentPositionParams params = pos_in(p_uri, p_pos);
  110. const LSP::DocumentSymbol *symbol = workspace->resolve_symbol(params);
  111. CHECK(symbol);
  112. if (symbol) {
  113. CHECK_EQ(symbol->uri, p_expected_uri);
  114. CHECK_EQ(symbol->name, p_expected_name);
  115. CHECK_EQ(symbol->selectionRange, p_expected_range);
  116. }
  117. return symbol;
  118. }
  119. struct InlineTestData {
  120. LSP::Range range;
  121. String text;
  122. String name;
  123. String ref;
  124. static bool try_parse(const Vector<String> &p_lines, const int p_line_number, InlineTestData &r_data) {
  125. String line = p_lines[p_line_number];
  126. RegEx regex = RegEx("^\\t*#[ |]*(?<range>(?<left><)?\\^+)(\\s+(?<name>(?!->)\\S+))?(\\s+->\\s+(?<ref>\\S+))?");
  127. Ref<RegExMatch> match = regex.search(line);
  128. if (match.is_null()) {
  129. return false;
  130. }
  131. // Find first line without leading comment above current line.
  132. int target_line = p_line_number;
  133. while (target_line >= 0) {
  134. String dedented = p_lines[target_line].lstrip("\t");
  135. if (!dedented.begins_with("#")) {
  136. break;
  137. }
  138. target_line--;
  139. }
  140. if (target_line < 0) {
  141. return false;
  142. }
  143. r_data.range.start.line = r_data.range.end.line = target_line;
  144. String marker = match->get_string("range");
  145. int i = line.find(marker);
  146. REQUIRE(i >= 0);
  147. r_data.range.start.character = i;
  148. if (!match->get_string("left").is_empty()) {
  149. // Include `#` (comment char) in range.
  150. r_data.range.start.character--;
  151. }
  152. r_data.range.end.character = i + marker.length();
  153. String target = p_lines[target_line];
  154. r_data.text = target.substr(r_data.range.start.character, r_data.range.end.character - r_data.range.start.character);
  155. r_data.name = match->get_string("name");
  156. r_data.ref = match->get_string("ref");
  157. return true;
  158. }
  159. };
  160. Vector<InlineTestData> read_tests(const String &p_path) {
  161. Error err;
  162. String source = FileAccess::get_file_as_string(p_path, &err);
  163. REQUIRE_MESSAGE(err == OK, vformat("Cannot read '%s'", p_path));
  164. // Format:
  165. // ```gdscript
  166. // var foo = bar + baz
  167. // # | | | | ^^^ name -> ref
  168. // # | | ^^^ -> ref
  169. // # ^^^ name
  170. //
  171. // func my_func():
  172. // # ^^^^^^^ name
  173. // var value = foo + 42
  174. // # ^^^^^ name
  175. // print(value)
  176. // # ^^^^^ -> ref
  177. // ```
  178. //
  179. // * `^`: Range marker.
  180. // * `name`: Unique name. Can contain any characters except whitespace chars.
  181. // * `ref`: Reference to unique name.
  182. //
  183. // Notes:
  184. // * If range should include first content-char (which is occupied by `#`): use `<` for next marker.
  185. // -> Range expands 1 to left (-> includes `#`).
  186. // * Note: Means: Range cannot be single char directly marked by `#`, but must be at least two chars (marked with `#<`).
  187. // * Comment must start at same ident as line its marked (-> because of tab alignment...).
  188. // * Use spaces to align after `#`! -> for correct alignment
  189. // * Between `#` and `^` can be spaces or `|` (to better visualize what's marked below).
  190. PackedStringArray lines = source.split("\n");
  191. PackedStringArray names;
  192. Vector<InlineTestData> data;
  193. for (int i = 0; i < lines.size(); i++) {
  194. InlineTestData d;
  195. if (InlineTestData::try_parse(lines, i, d)) {
  196. if (!d.name.is_empty()) {
  197. // Safety check: names must be unique.
  198. if (names.has(d.name)) {
  199. FAIL(vformat("Duplicated name '%s' in '%s'. Names must be unique!", d.name, p_path));
  200. }
  201. names.append(d.name);
  202. }
  203. data.append(d);
  204. }
  205. }
  206. return data;
  207. }
  208. void test_resolve_symbol(const String &p_uri, const InlineTestData &p_test_data, const Vector<InlineTestData> &p_all_data) {
  209. if (p_test_data.ref.is_empty()) {
  210. return;
  211. }
  212. 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()) {
  213. const InlineTestData *target = nullptr;
  214. for (int i = 0; i < p_all_data.size(); i++) {
  215. if (p_all_data[i].name == p_test_data.ref) {
  216. target = &p_all_data[i];
  217. break;
  218. }
  219. }
  220. REQUIRE_MESSAGE(target, vformat("No target for ref '%s'", p_test_data.ref));
  221. Ref<GDScriptWorkspace> workspace = GDScriptLanguageProtocol::get_singleton()->get_workspace();
  222. LSP::Position pos = p_test_data.range.start;
  223. SUBCASE("start of identifier") {
  224. pos.character = p_test_data.range.start.character;
  225. test_resolve_symbol_at(p_uri, pos, p_uri, target->text, target->range);
  226. }
  227. SUBCASE("inside identifier") {
  228. pos.character = (p_test_data.range.end.character + p_test_data.range.start.character) / 2;
  229. test_resolve_symbol_at(p_uri, pos, p_uri, target->text, target->range);
  230. }
  231. SUBCASE("end of identifier") {
  232. pos.character = p_test_data.range.end.character;
  233. test_resolve_symbol_at(p_uri, pos, p_uri, target->text, target->range);
  234. }
  235. }
  236. }
  237. Vector<InlineTestData> filter_ref_towards(const Vector<InlineTestData> &p_data, const String &p_name) {
  238. Vector<InlineTestData> res;
  239. for (const InlineTestData &d : p_data) {
  240. if (d.ref == p_name) {
  241. res.append(d);
  242. }
  243. }
  244. return res;
  245. }
  246. void test_resolve_symbols(const String &p_uri, const Vector<InlineTestData> &p_test_data, const Vector<InlineTestData> &p_all_data) {
  247. for (const InlineTestData &d : p_test_data) {
  248. test_resolve_symbol(p_uri, d, p_all_data);
  249. }
  250. }
  251. void assert_no_errors_in(const String &p_path) {
  252. Error err;
  253. String source = FileAccess::get_file_as_string(p_path, &err);
  254. REQUIRE_MESSAGE(err == OK, vformat("Cannot read '%s'", p_path));
  255. GDScriptParser parser;
  256. err = parser.parse(source, p_path, true);
  257. REQUIRE_MESSAGE(err == OK, vformat("Errors while parsing '%s'", p_path));
  258. GDScriptAnalyzer analyzer(&parser);
  259. err = analyzer.analyze();
  260. REQUIRE_MESSAGE(err == OK, vformat("Errors while analyzing '%s'", p_path));
  261. }
  262. inline LSP::Position lsp_pos(int line, int character) {
  263. LSP::Position p;
  264. p.line = line;
  265. p.character = character;
  266. return p;
  267. }
  268. void test_position_roundtrip(LSP::Position p_lsp, GodotPosition p_gd, const PackedStringArray &p_lines) {
  269. GodotPosition actual_gd = GodotPosition::from_lsp(p_lsp, p_lines);
  270. CHECK_EQ(p_gd, actual_gd);
  271. LSP::Position actual_lsp = p_gd.to_lsp(p_lines);
  272. CHECK_EQ(p_lsp, actual_lsp);
  273. }
  274. // Note:
  275. // * Cursor is BETWEEN chars
  276. // * `va|r` -> cursor between `a`&`r`
  277. // * `var`
  278. // ^
  279. // -> Character on `r` -> cursor between `a`&`r`s for tests:
  280. // * Line & Char:
  281. // * LSP: both 0-based
  282. // * Godot: both 1-based
  283. TEST_SUITE("[Modules][GDScript][LSP][Editor]") {
  284. TEST_CASE("Can convert positions to and from Godot") {
  285. String code = R"(extends Node
  286. var member := 42
  287. func f():
  288. var value := 42
  289. return value + member)";
  290. PackedStringArray lines = code.split("\n");
  291. SUBCASE("line after end") {
  292. LSP::Position lsp = lsp_pos(7, 0);
  293. GodotPosition gd(8, 1);
  294. test_position_roundtrip(lsp, gd, lines);
  295. }
  296. SUBCASE("first char in first line") {
  297. LSP::Position lsp = lsp_pos(0, 0);
  298. GodotPosition gd(1, 1);
  299. test_position_roundtrip(lsp, gd, lines);
  300. }
  301. SUBCASE("with tabs") {
  302. // On `v` in `value` in `var value := ...`.
  303. LSP::Position lsp = lsp_pos(5, 6);
  304. GodotPosition gd(6, 13);
  305. test_position_roundtrip(lsp, gd, lines);
  306. }
  307. SUBCASE("doesn't fail with column outside of character length") {
  308. LSP::Position lsp = lsp_pos(2, 100);
  309. GodotPosition::from_lsp(lsp, lines);
  310. GodotPosition gd(3, 100);
  311. gd.to_lsp(lines);
  312. }
  313. SUBCASE("doesn't fail with line outside of line length") {
  314. LSP::Position lsp = lsp_pos(200, 100);
  315. GodotPosition::from_lsp(lsp, lines);
  316. GodotPosition gd(300, 100);
  317. gd.to_lsp(lines);
  318. }
  319. SUBCASE("special case: zero column for root class") {
  320. GodotPosition gd(1, 0);
  321. LSP::Position expected = lsp_pos(0, 0);
  322. LSP::Position actual = gd.to_lsp(lines);
  323. CHECK_EQ(actual, expected);
  324. }
  325. SUBCASE("special case: zero line and column for root class") {
  326. GodotPosition gd(0, 0);
  327. LSP::Position expected = lsp_pos(0, 0);
  328. LSP::Position actual = gd.to_lsp(lines);
  329. CHECK_EQ(actual, expected);
  330. }
  331. SUBCASE("special case: negative line for root class") {
  332. GodotPosition gd(-1, 0);
  333. LSP::Position expected = lsp_pos(0, 0);
  334. LSP::Position actual = gd.to_lsp(lines);
  335. CHECK_EQ(actual, expected);
  336. }
  337. SUBCASE("special case: lines.length() + 1 for root class") {
  338. GodotPosition gd(lines.size() + 1, 0);
  339. LSP::Position expected = lsp_pos(lines.size(), 0);
  340. LSP::Position actual = gd.to_lsp(lines);
  341. CHECK_EQ(actual, expected);
  342. }
  343. }
  344. TEST_CASE("[workspace][resolve_symbol]") {
  345. EditorFileSystem *efs = memnew(EditorFileSystem);
  346. GDScriptLanguageProtocol *proto = initialize(root);
  347. REQUIRE(proto);
  348. Ref<GDScriptWorkspace> workspace = GDScriptLanguageProtocol::get_singleton()->get_workspace();
  349. {
  350. String path = "res://lsp/local_variables.gd";
  351. assert_no_errors_in(path);
  352. String uri = workspace->get_file_uri(path);
  353. Vector<InlineTestData> all_test_data = read_tests(path);
  354. SUBCASE("Can get correct ranges for public variables") {
  355. Vector<InlineTestData> test_data = filter_ref_towards(all_test_data, "member");
  356. test_resolve_symbols(uri, test_data, all_test_data);
  357. }
  358. SUBCASE("Can get correct ranges for local variables") {
  359. Vector<InlineTestData> test_data = filter_ref_towards(all_test_data, "test");
  360. test_resolve_symbols(uri, test_data, all_test_data);
  361. }
  362. SUBCASE("Can get correct ranges for local parameters") {
  363. Vector<InlineTestData> test_data = filter_ref_towards(all_test_data, "arg");
  364. test_resolve_symbols(uri, test_data, all_test_data);
  365. }
  366. }
  367. SUBCASE("Can get correct ranges for indented variables") {
  368. String path = "res://lsp/indentation.gd";
  369. assert_no_errors_in(path);
  370. String uri = workspace->get_file_uri(path);
  371. Vector<InlineTestData> all_test_data = read_tests(path);
  372. test_resolve_symbols(uri, all_test_data, all_test_data);
  373. }
  374. SUBCASE("Can get correct ranges for scopes") {
  375. String path = "res://lsp/scopes.gd";
  376. assert_no_errors_in(path);
  377. String uri = workspace->get_file_uri(path);
  378. Vector<InlineTestData> all_test_data = read_tests(path);
  379. test_resolve_symbols(uri, all_test_data, all_test_data);
  380. }
  381. SUBCASE("Can get correct ranges for lambda") {
  382. String path = "res://lsp/lambdas.gd";
  383. assert_no_errors_in(path);
  384. String uri = workspace->get_file_uri(path);
  385. Vector<InlineTestData> all_test_data = read_tests(path);
  386. test_resolve_symbols(uri, all_test_data, all_test_data);
  387. }
  388. SUBCASE("Can get correct ranges for inner class") {
  389. String path = "res://lsp/class.gd";
  390. assert_no_errors_in(path);
  391. String uri = workspace->get_file_uri(path);
  392. Vector<InlineTestData> all_test_data = read_tests(path);
  393. test_resolve_symbols(uri, all_test_data, all_test_data);
  394. }
  395. SUBCASE("Can get correct ranges for inner class") {
  396. String path = "res://lsp/enums.gd";
  397. assert_no_errors_in(path);
  398. String uri = workspace->get_file_uri(path);
  399. Vector<InlineTestData> all_test_data = read_tests(path);
  400. test_resolve_symbols(uri, all_test_data, all_test_data);
  401. }
  402. SUBCASE("Can get correct ranges for shadowing & shadowed variables") {
  403. String path = "res://lsp/shadowing_initializer.gd";
  404. assert_no_errors_in(path);
  405. String uri = workspace->get_file_uri(path);
  406. Vector<InlineTestData> all_test_data = read_tests(path);
  407. test_resolve_symbols(uri, all_test_data, all_test_data);
  408. }
  409. SUBCASE("Can get correct ranges for properties and getter/setter") {
  410. String path = "res://lsp/properties.gd";
  411. assert_no_errors_in(path);
  412. String uri = workspace->get_file_uri(path);
  413. Vector<InlineTestData> all_test_data = read_tests(path);
  414. test_resolve_symbols(uri, all_test_data, all_test_data);
  415. }
  416. memdelete(proto);
  417. memdelete(efs);
  418. finish_language();
  419. }
  420. TEST_CASE("[workspace][document_symbol]") {
  421. EditorFileSystem *efs = memnew(EditorFileSystem);
  422. GDScriptLanguageProtocol *proto = initialize(root);
  423. REQUIRE(proto);
  424. SUBCASE("selectionRange of root class must be inside range") {
  425. LocalVector<String> paths = {
  426. "res://lsp/first_line_comment.gd", // Comment on first line
  427. "res://lsp/first_line_class_name.gd", // class_name (and thus selection range) before extends
  428. };
  429. for (const String &path : paths) {
  430. assert_no_errors_in(path);
  431. GDScriptLanguageProtocol::get_singleton()->get_workspace()->parse_local_script(path);
  432. ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_workspace()->parse_results[path];
  433. REQUIRE(parser);
  434. LSP::DocumentSymbol cls = parser->get_symbols();
  435. 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)));
  436. 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)));
  437. }
  438. }
  439. SUBCASE("Documentation is correctly set") {
  440. String path = "res://lsp/doc_comments.gd";
  441. assert_no_errors_in(path);
  442. GDScriptLanguageProtocol::get_singleton()->get_workspace()->parse_local_script(path);
  443. ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_workspace()->parse_results[path];
  444. REQUIRE(parser);
  445. LSP::DocumentSymbol cls = parser->get_symbols();
  446. REQUIRE(cls.documentation.contains("brief"));
  447. REQUIRE(cls.documentation.contains("description"));
  448. REQUIRE(cls.documentation.contains("t1"));
  449. REQUIRE(cls.documentation.contains("t2"));
  450. REQUIRE(cls.documentation.contains("t3"));
  451. }
  452. memdelete(proto);
  453. memdelete(efs);
  454. finish_language();
  455. }
  456. TEST_CASE("BBCode to markdown conversion") {
  457. // This tests the conversion from BBCode docstrings to the markdown markup sent to
  458. // the LSP client on documentation requests
  459. // Basic formatting
  460. CHECK_EQ(LSP::marked_documentation("[b]bold[/b]"), "**bold**");
  461. CHECK_EQ(LSP::marked_documentation("[i]italic[/i]"), "*italic*");
  462. CHECK_EQ(LSP::marked_documentation("[u]underline[/u]"), "__underline__");
  463. CHECK_EQ(LSP::marked_documentation("[s]strikethrough[/s]"), "~~strikethrough~~");
  464. CHECK_EQ(LSP::marked_documentation("[code]code[/code]"), "`code`");
  465. CHECK_EQ(LSP::marked_documentation("[kbd]Ctrl + S[/kbd]"), "`Ctrl + S`");
  466. // Line breaks. We insert paragraphs for [br] because the BBCode to
  467. // markdown conversion function simply makes the conversion line-wise and
  468. // we don't distinguish markdown inline elements and blocks.
  469. CHECK_EQ(LSP::marked_documentation("Line1[br]Line2"), "Line1\n\nLine2");
  470. // These tags (center, color, font) aren't supported in markdown and should be stripped.
  471. CHECK_EQ(LSP::marked_documentation("[center]Centered text[/center]"), "Centered text");
  472. CHECK_EQ(LSP::marked_documentation("[color=red]red text[/color]"), "red text");
  473. CHECK_EQ(LSP::marked_documentation("[font=Arial]Arial text[/font]"), "Arial text");
  474. // The following tests are for all the link patterns specific to Godot's built-in docs that we render as inline code.
  475. CHECK_EQ(LSP::marked_documentation("Class link: [Node2D], [Sprite2D]"), "Class link: `Node2D`, `Sprite2D`");
  476. CHECK_EQ(LSP::marked_documentation("Single class [RigidBody2D]"), "Single class `RigidBody2D`");
  477. CHECK_EQ(LSP::marked_documentation("[method Node2D.set_position]"), "`Node2D.set_position`");
  478. CHECK_EQ(LSP::marked_documentation("[member Node2D.position]"), "`Node2D.position`");
  479. CHECK_EQ(LSP::marked_documentation("[signal Node.ready]"), "`Node.ready`");
  480. CHECK_EQ(LSP::marked_documentation("[constant Color.RED]"), "`Color.RED`");
  481. CHECK_EQ(LSP::marked_documentation("[enum Node.ProcessMode]"), "`Node.ProcessMode`");
  482. CHECK_EQ(LSP::marked_documentation("[annotation @GDScript.@export]"), "`@GDScript.@export`");
  483. CHECK_EQ(LSP::marked_documentation("[constructor Vector2.Vector2]"), "`Vector2.Vector2`");
  484. CHECK_EQ(LSP::marked_documentation("[operator Vector2.operator +]"), "`Vector2.operator +`");
  485. CHECK_EQ(LSP::marked_documentation("[theme_item Button.font]"), "`Button.font`");
  486. CHECK_EQ(LSP::marked_documentation("[param delta]"), "`delta`");
  487. // Markdown links
  488. CHECK_EQ(LSP::marked_documentation("[url=https://godotengine.org]link to Godot Engine[/url]"),
  489. "[link to Godot Engine](https://godotengine.org)");
  490. CHECK_EQ(LSP::marked_documentation("[url]https://godotengine.org/[/url]"),
  491. "[https://godotengine.org/](https://godotengine.org/)");
  492. // Code listings
  493. CHECK_EQ(LSP::marked_documentation("[codeblock]\nfunc test():\n print(\"Hello, Godot!\")\n[/codeblock]"),
  494. "```gdscript\nfunc test():\n print(\"Hello, Godot!\")\n```");
  495. CHECK_EQ(LSP::marked_documentation("[codeblock lang=csharp]\npublic void Test()\n{\n GD.Print(\"Hello, Godot!\");\n}\n[/codeblock]"),
  496. "```csharp\npublic void Test()\n{\n GD.Print(\"Hello, Godot!\");\n}\n```");
  497. // Code listings with multiple languages (the codeblocks tag is used in the built-in reference)
  498. // When [codeblocks] is used, we only convert the [gdscript] tag to a code block like the built-in editor.
  499. // NOTE: There is always a GDScript code listing in the built-in class reference.
  500. CHECK_EQ(LSP::marked_documentation("[codeblocks]\n[gdscript]\nprint(hash(\"a\")) # Prints 177670\n[/gdscript]\n[csharp]\nGD.Print(GD.Hash(\"a\")); // Prints 177670\n[/csharp]\n[/codeblocks]"),
  501. "```gdscript\nprint(hash(\"a\")) # Prints 177670\n```\n");
  502. // lb and rb are used to insert literal square brackets in markdown.
  503. CHECK_EQ(LSP::marked_documentation("[lb]literal brackets[rb]"), "\\[literal brackets\\]");
  504. CHECK_EQ(LSP::marked_documentation("[lb]literal[rb] with [ClassName]"), "\\[literal\\] with `ClassName`");
  505. // We have to be careful that different patterns don't conflict with each
  506. // other, especially with urls that use brackets in markdown.
  507. CHECK_EQ(LSP::marked_documentation("Class [Sprite2D] with [url=https://godotengine.org]link[/url]"),
  508. "Class `Sprite2D` with [link](https://godotengine.org)");
  509. }
  510. }
  511. } // namespace GDScriptTests
  512. #endif // MODULE_JSONRPC_ENABLED
  513. #endif // TOOLS_ENABLED