gdscript_workspace.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  1. /**************************************************************************/
  2. /* gdscript_workspace.cpp */
  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. #include "gdscript_workspace.h"
  31. #include "../gdscript.h"
  32. #include "../gdscript_parser.h"
  33. #include "gdscript_language_protocol.h"
  34. #include "core/config/project_settings.h"
  35. #include "core/object/script_language.h"
  36. #include "editor/doc/doc_tools.h"
  37. #include "editor/doc/editor_help.h"
  38. #include "editor/editor_node.h"
  39. #include "editor/file_system/editor_file_system.h"
  40. #include "editor/settings/editor_settings.h"
  41. #include "scene/resources/packed_scene.h"
  42. void GDScriptWorkspace::_bind_methods() {
  43. ClassDB::bind_method(D_METHOD("apply_new_signal"), &GDScriptWorkspace::apply_new_signal);
  44. ClassDB::bind_method(D_METHOD("get_file_path", "uri"), &GDScriptWorkspace::get_file_path);
  45. ClassDB::bind_method(D_METHOD("get_file_uri", "path"), &GDScriptWorkspace::get_file_uri);
  46. ClassDB::bind_method(D_METHOD("publish_diagnostics", "path"), &GDScriptWorkspace::publish_diagnostics);
  47. ClassDB::bind_method(D_METHOD("generate_script_api", "path"), &GDScriptWorkspace::generate_script_api);
  48. #ifndef DISABLE_DEPRECATED
  49. ClassDB::bind_method(D_METHOD("didDeleteFiles"), &GDScriptWorkspace::didDeleteFiles);
  50. ClassDB::bind_method(D_METHOD("parse_script", "path", "content"), &GDScriptWorkspace::parse_script);
  51. ClassDB::bind_method(D_METHOD("parse_local_script", "path"), &GDScriptWorkspace::parse_script);
  52. #endif
  53. }
  54. void GDScriptWorkspace::apply_new_signal(Object *obj, String function, PackedStringArray args) {
  55. Ref<Script> scr = obj->get_script();
  56. if (scr->get_language()->get_name() != "GDScript") {
  57. return;
  58. }
  59. String function_signature = "func " + function;
  60. String source = scr->get_source_code();
  61. if (source.contains(function_signature)) {
  62. return;
  63. }
  64. int first_class = source.find("\nclass ");
  65. int start_line = 0;
  66. if (first_class != -1) {
  67. start_line = source.substr(0, first_class).split("\n").size();
  68. } else {
  69. start_line = source.split("\n").size();
  70. }
  71. String function_body = "\n\n" + function_signature + "(";
  72. for (int i = 0; i < args.size(); ++i) {
  73. function_body += args[i];
  74. if (i < args.size() - 1) {
  75. function_body += ", ";
  76. }
  77. }
  78. function_body += ")";
  79. if (EditorSettings::get_singleton()->get_setting("text_editor/completion/add_type_hints")) {
  80. function_body += " -> void";
  81. }
  82. function_body += ":\n\tpass # Replace with function body.\n";
  83. LSP::TextEdit text_edit;
  84. if (first_class != -1) {
  85. function_body += "\n\n";
  86. }
  87. text_edit.range.end.line = text_edit.range.start.line = start_line;
  88. text_edit.newText = function_body;
  89. String uri = get_file_uri(scr->get_path());
  90. LSP::ApplyWorkspaceEditParams params;
  91. params.edit.add_edit(uri, text_edit);
  92. GDScriptLanguageProtocol::get_singleton()->request_client("workspace/applyEdit", params.to_json());
  93. }
  94. const LSP::DocumentSymbol *GDScriptWorkspace::get_native_symbol(const String &p_class, const String &p_member) const {
  95. StringName class_name = p_class;
  96. StringName empty;
  97. while (class_name != empty) {
  98. if (HashMap<StringName, LSP::DocumentSymbol>::ConstIterator E = native_symbols.find(class_name)) {
  99. const LSP::DocumentSymbol &class_symbol = E->value;
  100. if (p_member.is_empty()) {
  101. return &class_symbol;
  102. } else {
  103. for (int i = 0; i < class_symbol.children.size(); i++) {
  104. const LSP::DocumentSymbol &symbol = class_symbol.children[i];
  105. if (symbol.name == p_member) {
  106. return &symbol;
  107. }
  108. }
  109. }
  110. }
  111. // Might contain pseudo classes like @GDScript that only exist in documentation.
  112. if (ClassDB::class_exists(class_name)) {
  113. class_name = ClassDB::get_parent_class(class_name);
  114. } else {
  115. break;
  116. }
  117. }
  118. return nullptr;
  119. }
  120. const LSP::DocumentSymbol *GDScriptWorkspace::get_script_symbol(const String &p_path) const {
  121. ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(p_path);
  122. if (parser) {
  123. return &(parser->get_symbols());
  124. }
  125. return nullptr;
  126. }
  127. const LSP::DocumentSymbol *GDScriptWorkspace::get_parameter_symbol(const LSP::DocumentSymbol *p_parent, const String &symbol_identifier) {
  128. for (int i = 0; i < p_parent->children.size(); ++i) {
  129. const LSP::DocumentSymbol *parameter_symbol = &p_parent->children[i];
  130. if (!parameter_symbol->detail.is_empty() && parameter_symbol->name == symbol_identifier) {
  131. return parameter_symbol;
  132. }
  133. }
  134. return nullptr;
  135. }
  136. const LSP::DocumentSymbol *GDScriptWorkspace::get_local_symbol_at(const ExtendGDScriptParser *p_parser, const String &p_symbol_identifier, const LSP::Position p_position) {
  137. // Go down and pick closest `DocumentSymbol` with `p_symbol_identifier`.
  138. const LSP::DocumentSymbol *current = &p_parser->get_symbols();
  139. const LSP::DocumentSymbol *best_match = nullptr;
  140. while (current) {
  141. if (current->name == p_symbol_identifier) {
  142. if (current->selectionRange.contains(p_position)) {
  143. // Exact match: pos is ON symbol decl identifier.
  144. return current;
  145. }
  146. best_match = current;
  147. }
  148. const LSP::DocumentSymbol *parent = current;
  149. current = nullptr;
  150. for (const LSP::DocumentSymbol &child : parent->children) {
  151. if (child.range.contains(p_position)) {
  152. current = &child;
  153. break;
  154. }
  155. }
  156. }
  157. return best_match;
  158. }
  159. void GDScriptWorkspace::reload_all_workspace_scripts() {
  160. List<String> paths;
  161. list_script_files("res://", paths);
  162. for (const String &path : paths) {
  163. ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(path);
  164. if (parser == nullptr || parser->parse_result != OK) {
  165. String err_msg = "LSP: Failed to parse script: " + path;
  166. if (parser) {
  167. err_msg += "\n" + parser->get_errors().front()->get().message;
  168. }
  169. ERR_PRINT(err_msg);
  170. }
  171. }
  172. }
  173. void GDScriptWorkspace::list_script_files(const String &p_root_dir, List<String> &r_files) {
  174. Error err;
  175. Ref<DirAccess> dir = DirAccess::open(p_root_dir, &err);
  176. if (OK != err) {
  177. return;
  178. }
  179. // Ignore scripts in directories with a .gdignore file.
  180. if (dir->file_exists(".gdignore")) {
  181. return;
  182. }
  183. dir->list_dir_begin();
  184. String file_name = dir->get_next();
  185. while (file_name.length()) {
  186. if (dir->current_is_dir() && file_name != "." && file_name != ".." && file_name != "./") {
  187. list_script_files(p_root_dir.path_join(file_name), r_files);
  188. } else if (file_name.ends_with(".gd")) {
  189. String script_file = p_root_dir.path_join(file_name);
  190. r_files.push_back(script_file);
  191. }
  192. file_name = dir->get_next();
  193. }
  194. }
  195. #define HANDLE_DOC(m_string) ((is_native ? DTR(m_string) : (m_string)).strip_edges())
  196. Error GDScriptWorkspace::initialize() {
  197. if (initialized) {
  198. return OK;
  199. }
  200. DocTools *doc = EditorHelp::get_doc_data();
  201. for (const KeyValue<String, DocData::ClassDoc> &E : doc->class_list) {
  202. const DocData::ClassDoc &class_data = E.value;
  203. const bool is_native = !class_data.is_script_doc;
  204. LSP::DocumentSymbol class_symbol;
  205. String class_name = E.key;
  206. class_symbol.name = class_name;
  207. class_symbol.native_class = class_name;
  208. class_symbol.kind = LSP::SymbolKind::Class;
  209. class_symbol.detail = String("<Native> class ") + class_name;
  210. if (!class_data.inherits.is_empty()) {
  211. class_symbol.detail += " extends " + class_data.inherits;
  212. }
  213. class_symbol.documentation = HANDLE_DOC(class_data.brief_description) + "\n" + HANDLE_DOC(class_data.description);
  214. for (int i = 0; i < class_data.constants.size(); i++) {
  215. const DocData::ConstantDoc &const_data = class_data.constants[i];
  216. LSP::DocumentSymbol symbol;
  217. symbol.name = const_data.name;
  218. symbol.native_class = class_name;
  219. symbol.kind = LSP::SymbolKind::Constant;
  220. symbol.detail = "const " + class_name + "." + const_data.name;
  221. if (const_data.enumeration.length()) {
  222. symbol.detail += ": " + const_data.enumeration;
  223. }
  224. symbol.detail += " = " + const_data.value;
  225. symbol.documentation = HANDLE_DOC(const_data.description);
  226. class_symbol.children.push_back(symbol);
  227. }
  228. for (int i = 0; i < class_data.properties.size(); i++) {
  229. const DocData::PropertyDoc &data = class_data.properties[i];
  230. LSP::DocumentSymbol symbol;
  231. symbol.name = data.name;
  232. symbol.native_class = class_name;
  233. symbol.kind = LSP::SymbolKind::Property;
  234. symbol.detail = "var " + class_name + "." + data.name;
  235. if (data.enumeration.length()) {
  236. symbol.detail += ": " + data.enumeration;
  237. } else {
  238. symbol.detail += ": " + data.type;
  239. }
  240. symbol.documentation = HANDLE_DOC(data.description);
  241. class_symbol.children.push_back(symbol);
  242. }
  243. for (int i = 0; i < class_data.theme_properties.size(); i++) {
  244. const DocData::ThemeItemDoc &data = class_data.theme_properties[i];
  245. LSP::DocumentSymbol symbol;
  246. symbol.name = data.name;
  247. symbol.native_class = class_name;
  248. symbol.kind = LSP::SymbolKind::Property;
  249. symbol.detail = "<Theme> var " + class_name + "." + data.name + ": " + data.type;
  250. symbol.documentation = HANDLE_DOC(data.description);
  251. class_symbol.children.push_back(symbol);
  252. }
  253. Vector<DocData::MethodDoc> method_likes;
  254. method_likes.append_array(class_data.methods);
  255. method_likes.append_array(class_data.annotations);
  256. const int constructors_start_idx = method_likes.size();
  257. method_likes.append_array(class_data.constructors);
  258. const int operator_start_idx = method_likes.size();
  259. method_likes.append_array(class_data.operators);
  260. const int signal_start_idx = method_likes.size();
  261. method_likes.append_array(class_data.signals);
  262. for (int i = 0; i < method_likes.size(); i++) {
  263. const DocData::MethodDoc &data = method_likes[i];
  264. LSP::DocumentSymbol symbol;
  265. symbol.name = data.name;
  266. symbol.native_class = class_name;
  267. if (i >= signal_start_idx) {
  268. symbol.kind = LSP::SymbolKind::Event;
  269. } else if (i >= operator_start_idx) {
  270. symbol.kind = LSP::SymbolKind::Operator;
  271. } else if (i >= constructors_start_idx) {
  272. symbol.kind = LSP::SymbolKind::Constructor;
  273. } else {
  274. symbol.kind = LSP::SymbolKind::Method;
  275. }
  276. String params = "";
  277. bool arg_default_value_started = false;
  278. for (int j = 0; j < data.arguments.size(); j++) {
  279. const DocData::ArgumentDoc &arg = data.arguments[j];
  280. LSP::DocumentSymbol symbol_arg;
  281. symbol_arg.name = arg.name;
  282. symbol_arg.kind = LSP::SymbolKind::Variable;
  283. symbol_arg.detail = arg.type;
  284. if (!arg_default_value_started && !arg.default_value.is_empty()) {
  285. arg_default_value_started = true;
  286. }
  287. String arg_str = arg.name + ": " + arg.type;
  288. if (arg_default_value_started) {
  289. arg_str += " = " + arg.default_value;
  290. }
  291. if (j < data.arguments.size() - 1) {
  292. arg_str += ", ";
  293. }
  294. params += arg_str;
  295. symbol.children.push_back(symbol_arg);
  296. }
  297. if (data.qualifiers.contains("vararg")) {
  298. params += params.is_empty() ? "..." : ", ...";
  299. }
  300. String return_type = data.return_type;
  301. if (return_type.is_empty()) {
  302. return_type = "void";
  303. }
  304. symbol.detail = "func " + class_name + "." + data.name + "(" + params + ") -> " + return_type;
  305. symbol.documentation = HANDLE_DOC(data.description);
  306. class_symbol.children.push_back(symbol);
  307. }
  308. native_symbols.insert(class_name, class_symbol);
  309. }
  310. reload_all_workspace_scripts();
  311. if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) {
  312. for (const KeyValue<StringName, LSP::DocumentSymbol> &E : native_symbols) {
  313. ClassMembers members;
  314. const LSP::DocumentSymbol &class_symbol = E.value;
  315. for (int i = 0; i < class_symbol.children.size(); i++) {
  316. const LSP::DocumentSymbol &symbol = class_symbol.children[i];
  317. members.insert(symbol.name, &symbol);
  318. }
  319. native_members.insert(E.key, members);
  320. }
  321. }
  322. EditorNode *editor_node = EditorNode::get_singleton();
  323. editor_node->connect("script_add_function_request", callable_mp(this, &GDScriptWorkspace::apply_new_signal));
  324. return OK;
  325. }
  326. static bool is_valid_rename_target(const LSP::DocumentSymbol *p_symbol) {
  327. // Must be valid symbol.
  328. if (!p_symbol) {
  329. return false;
  330. }
  331. // Cannot rename builtin.
  332. if (!p_symbol->native_class.is_empty()) {
  333. return false;
  334. }
  335. // Source must be available.
  336. if (p_symbol->script_path.is_empty()) {
  337. return false;
  338. }
  339. return true;
  340. }
  341. Dictionary GDScriptWorkspace::rename(const LSP::TextDocumentPositionParams &p_doc_pos, const String &new_name) {
  342. LSP::WorkspaceEdit edit;
  343. const LSP::DocumentSymbol *reference_symbol = resolve_symbol(p_doc_pos);
  344. if (is_valid_rename_target(reference_symbol)) {
  345. Vector<LSP::Location> usages = find_all_usages(*reference_symbol);
  346. for (int i = 0; i < usages.size(); ++i) {
  347. LSP::Location loc = usages[i];
  348. edit.add_change(loc.uri, loc.range.start.line, loc.range.start.character, loc.range.end.character, new_name);
  349. }
  350. }
  351. return edit.to_json();
  352. }
  353. bool GDScriptWorkspace::can_rename(const LSP::TextDocumentPositionParams &p_doc_pos, LSP::DocumentSymbol &r_symbol, LSP::Range &r_range) {
  354. const LSP::DocumentSymbol *reference_symbol = resolve_symbol(p_doc_pos);
  355. if (!is_valid_rename_target(reference_symbol)) {
  356. return false;
  357. }
  358. String path = get_file_path(p_doc_pos.textDocument.uri);
  359. const ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(path);
  360. if (parser) {
  361. _ALLOW_DISCARD_ parser->get_identifier_under_position(p_doc_pos.position, r_range);
  362. r_symbol = *reference_symbol;
  363. return true;
  364. }
  365. return false;
  366. }
  367. Vector<LSP::Location> GDScriptWorkspace::find_usages_in_file(const LSP::DocumentSymbol &p_symbol, const String &p_file_path) {
  368. Vector<LSP::Location> usages;
  369. String identifier = p_symbol.name;
  370. const ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(p_file_path);
  371. if (parser) {
  372. const PackedStringArray &content = parser->get_lines();
  373. for (int i = 0; i < content.size(); ++i) {
  374. String line = content[i];
  375. int character = line.find(identifier);
  376. while (character > -1) {
  377. LSP::TextDocumentPositionParams params;
  378. LSP::TextDocumentIdentifier text_doc;
  379. text_doc.uri = get_file_uri(p_file_path);
  380. params.textDocument = text_doc;
  381. params.position.line = i;
  382. params.position.character = character;
  383. const LSP::DocumentSymbol *other_symbol = resolve_symbol(params);
  384. if (other_symbol == &p_symbol) {
  385. LSP::Location loc;
  386. loc.uri = text_doc.uri;
  387. loc.range.start = params.position;
  388. loc.range.end.line = params.position.line;
  389. loc.range.end.character = params.position.character + identifier.length();
  390. usages.append(loc);
  391. }
  392. character = line.find(identifier, character + 1);
  393. }
  394. }
  395. }
  396. return usages;
  397. }
  398. Vector<LSP::Location> GDScriptWorkspace::find_all_usages(const LSP::DocumentSymbol &p_symbol) {
  399. if (p_symbol.local) {
  400. // Only search in current document.
  401. return find_usages_in_file(p_symbol, p_symbol.script_path);
  402. }
  403. // Search in all documents.
  404. List<String> paths;
  405. list_script_files("res://", paths);
  406. Vector<LSP::Location> usages;
  407. for (const String &path : paths) {
  408. usages.append_array(find_usages_in_file(p_symbol, path));
  409. }
  410. return usages;
  411. }
  412. String GDScriptWorkspace::get_file_path(const String &p_uri) {
  413. int port;
  414. String scheme;
  415. String host;
  416. String encoded_path;
  417. String fragment;
  418. // Don't use the returned error, the result isn't OK for URIs that are not valid web URLs.
  419. p_uri.parse_url(scheme, host, port, encoded_path, fragment);
  420. // TODO: Make the parsing RFC-3986 compliant.
  421. ERR_FAIL_COND_V_MSG(scheme != "file" && scheme != "file:" && scheme != "file://", String(), "LSP: The language server only supports the file protocol: " + p_uri);
  422. // Treat host like authority for now and ignore the port. It's an edge case for invalid file URI's anyway.
  423. ERR_FAIL_COND_V_MSG(host != "" && host != "localhost", String(), "LSP: The language server does not support nonlocal files: " + p_uri);
  424. // If query or fragment are present, the URI is not a valid file URI as per RFC-8089.
  425. // We currently don't handle the query and it will be part of the path. However,
  426. // this should not be a problem for a correct file URI.
  427. ERR_FAIL_COND_V_MSG(fragment != "", String(), "LSP: Received malformed file URI: " + p_uri);
  428. String canonical_res = ProjectSettings::get_singleton()->get_resource_path();
  429. String simple_path = encoded_path.uri_file_decode().simplify_path();
  430. // First try known paths that point to res://, to reduce file system interaction.
  431. bool res_adjusted = false;
  432. for (const String &res_path : absolute_res_paths) {
  433. if (simple_path.begins_with(res_path)) {
  434. res_adjusted = true;
  435. simple_path = "res://" + simple_path.substr(res_path.size());
  436. break;
  437. }
  438. }
  439. // Traverse the path and compare each directory with res://
  440. if (!res_adjusted) {
  441. Ref<DirAccess> dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  442. int offset = 0;
  443. while (offset <= simple_path.length()) {
  444. offset = simple_path.find_char('/', offset);
  445. if (offset == -1) {
  446. offset = simple_path.length();
  447. }
  448. String part = simple_path.substr(0, offset);
  449. if (!part.is_empty()) {
  450. bool is_equal = dir->is_equivalent(canonical_res, part);
  451. if (is_equal) {
  452. absolute_res_paths.insert(part);
  453. res_adjusted = true;
  454. simple_path = "res://" + simple_path.substr(offset + 1);
  455. break;
  456. }
  457. }
  458. offset += 1;
  459. }
  460. // Could not resolve the path to the project.
  461. if (!res_adjusted) {
  462. return simple_path;
  463. }
  464. }
  465. // Resolve the file inside of the project using EditorFileSystem.
  466. EditorFileSystemDirectory *editor_dir;
  467. int file_idx;
  468. editor_dir = EditorFileSystem::get_singleton()->find_file(simple_path, &file_idx);
  469. if (editor_dir) {
  470. return editor_dir->get_file_path(file_idx);
  471. }
  472. return simple_path;
  473. }
  474. String GDScriptWorkspace::get_file_uri(const String &p_path) const {
  475. String path = ProjectSettings::get_singleton()->globalize_path(p_path).lstrip("/");
  476. LocalVector<String> encoded_parts;
  477. for (const String &part : path.split("/")) {
  478. encoded_parts.push_back(part.uri_encode());
  479. }
  480. // Always return file URI's with authority part (encoding drive letters with leading slash), to maintain compat with RFC-1738 which required it.
  481. return "file:///" + String("/").join(Vector<String>(encoded_parts));
  482. }
  483. void GDScriptWorkspace::publish_diagnostics(const String &p_path) {
  484. Dictionary params;
  485. Array errors;
  486. const ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(p_path);
  487. if (parser) {
  488. const Vector<LSP::Diagnostic> &list = parser->get_diagnostics();
  489. errors.resize(list.size());
  490. for (int i = 0; i < list.size(); ++i) {
  491. errors[i] = list[i].to_json();
  492. }
  493. }
  494. params["diagnostics"] = errors;
  495. params["uri"] = get_file_uri(p_path);
  496. GDScriptLanguageProtocol::get_singleton()->notify_client("textDocument/publishDiagnostics", params);
  497. }
  498. void GDScriptWorkspace::_get_owners(EditorFileSystemDirectory *efsd, String p_path, List<String> &owners) {
  499. if (!efsd) {
  500. return;
  501. }
  502. for (int i = 0; i < efsd->get_subdir_count(); i++) {
  503. _get_owners(efsd->get_subdir(i), p_path, owners);
  504. }
  505. for (int i = 0; i < efsd->get_file_count(); i++) {
  506. Vector<String> deps = efsd->get_file_deps(i);
  507. bool found = false;
  508. for (int j = 0; j < deps.size(); j++) {
  509. if (deps[j] == p_path) {
  510. found = true;
  511. break;
  512. }
  513. }
  514. if (!found) {
  515. continue;
  516. }
  517. owners.push_back(efsd->get_file_path(i));
  518. }
  519. }
  520. Node *GDScriptWorkspace::_get_owner_scene_node(String p_path) {
  521. Node *owner_scene_node = nullptr;
  522. List<String> owners;
  523. _get_owners(EditorFileSystem::get_singleton()->get_filesystem(), p_path, owners);
  524. for (const String &owner : owners) {
  525. NodePath owner_path = owner;
  526. Ref<Resource> owner_res = ResourceLoader::load(String(owner_path));
  527. if (Object::cast_to<PackedScene>(owner_res.ptr())) {
  528. Ref<PackedScene> owner_packed_scene = Ref<PackedScene>(Object::cast_to<PackedScene>(*owner_res));
  529. owner_scene_node = owner_packed_scene->instantiate();
  530. break;
  531. }
  532. }
  533. return owner_scene_node;
  534. }
  535. void GDScriptWorkspace::completion(const LSP::CompletionParams &p_params, List<ScriptLanguage::CodeCompletionOption> *r_options) {
  536. String path = get_file_path(p_params.textDocument.uri);
  537. String call_hint;
  538. bool forced = false;
  539. const ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(path);
  540. if (parser) {
  541. Node *owner_scene_node = _get_owner_scene_node(path);
  542. Array stack;
  543. Node *current = nullptr;
  544. if (owner_scene_node != nullptr) {
  545. stack.push_back(owner_scene_node);
  546. while (!stack.is_empty()) {
  547. current = Object::cast_to<Node>(stack.pop_back());
  548. Ref<GDScript> scr = current->get_script();
  549. if (scr.is_valid() && GDScript::is_canonically_equal_paths(scr->get_path(), path)) {
  550. break;
  551. }
  552. for (int i = 0; i < current->get_child_count(); ++i) {
  553. stack.push_back(current->get_child(i));
  554. }
  555. }
  556. Ref<GDScript> scr = current->get_script();
  557. if (scr.is_null() || !GDScript::is_canonically_equal_paths(scr->get_path(), path)) {
  558. current = owner_scene_node;
  559. }
  560. }
  561. String code = parser->get_text_for_completion(p_params.position);
  562. GDScriptLanguage::get_singleton()->complete_code(code, path, current, r_options, forced, call_hint);
  563. if (owner_scene_node) {
  564. memdelete(owner_scene_node);
  565. }
  566. }
  567. }
  568. const LSP::DocumentSymbol *GDScriptWorkspace::resolve_symbol(const LSP::TextDocumentPositionParams &p_doc_pos, const String &p_symbol_name, bool p_func_required) {
  569. const LSP::DocumentSymbol *symbol = nullptr;
  570. String path = get_file_path(p_doc_pos.textDocument.uri);
  571. const ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(path);
  572. if (parser) {
  573. String symbol_identifier = p_symbol_name;
  574. if (symbol_identifier.get_slice_count("(") > 0) {
  575. symbol_identifier = symbol_identifier.get_slicec('(', 0);
  576. }
  577. LSP::Position pos = p_doc_pos.position;
  578. if (symbol_identifier.is_empty()) {
  579. LSP::Range range;
  580. symbol_identifier = parser->get_identifier_under_position(p_doc_pos.position, range);
  581. pos.character = range.end.character;
  582. }
  583. if (!symbol_identifier.is_empty()) {
  584. if (ScriptServer::is_global_class(symbol_identifier)) {
  585. String class_path = ScriptServer::get_global_class_path(symbol_identifier);
  586. symbol = get_script_symbol(class_path);
  587. } else {
  588. ScriptLanguage::LookupResult ret;
  589. if (symbol_identifier == "new" && parser->get_lines()[p_doc_pos.position.line].remove_chars(" \t").contains("new(")) {
  590. symbol_identifier = "_init";
  591. }
  592. if (OK == GDScriptLanguage::get_singleton()->lookup_code(parser->get_text_for_lookup_symbol(pos, symbol_identifier, p_func_required), symbol_identifier, path, nullptr, ret)) {
  593. if (ret.location >= 0) {
  594. String target_script_path = path;
  595. if (ret.script.is_valid()) {
  596. target_script_path = ret.script->get_path();
  597. } else if (!ret.script_path.is_empty()) {
  598. target_script_path = ret.script_path;
  599. }
  600. const ExtendGDScriptParser *target_parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(target_script_path);
  601. if (target_parser) {
  602. symbol = target_parser->get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(ret.location), symbol_identifier);
  603. if (symbol) {
  604. switch (symbol->kind) {
  605. case LSP::SymbolKind::Function: {
  606. if (symbol->name != symbol_identifier) {
  607. symbol = get_parameter_symbol(symbol, symbol_identifier);
  608. }
  609. } break;
  610. }
  611. }
  612. }
  613. } else {
  614. String member = ret.class_member;
  615. if (member.is_empty() && symbol_identifier != ret.class_name) {
  616. member = symbol_identifier;
  617. }
  618. symbol = get_native_symbol(ret.class_name, member);
  619. }
  620. } else {
  621. symbol = get_local_symbol_at(parser, symbol_identifier, p_doc_pos.position);
  622. if (!symbol) {
  623. symbol = parser->get_member_symbol(symbol_identifier);
  624. }
  625. }
  626. }
  627. }
  628. }
  629. return symbol;
  630. }
  631. const LSP::DocumentSymbol *GDScriptWorkspace::resolve_native_symbol(const LSP::NativeSymbolInspectParams &p_params) {
  632. if (HashMap<StringName, LSP::DocumentSymbol>::Iterator E = native_symbols.find(p_params.native_class)) {
  633. const LSP::DocumentSymbol &symbol = E->value;
  634. if (p_params.symbol_name.is_empty() || p_params.symbol_name == symbol.name) {
  635. return &symbol;
  636. }
  637. for (int i = 0; i < symbol.children.size(); ++i) {
  638. if (symbol.children[i].name == p_params.symbol_name) {
  639. return &(symbol.children[i]);
  640. }
  641. }
  642. }
  643. return nullptr;
  644. }
  645. void GDScriptWorkspace::resolve_document_links(const String &p_uri, List<LSP::DocumentLink> &r_list) {
  646. const ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(get_file_path(p_uri));
  647. if (parser && parser->parse_result == Error::OK) {
  648. const List<LSP::DocumentLink> &links = parser->get_document_links();
  649. for (const LSP::DocumentLink &E : links) {
  650. r_list.push_back(E);
  651. }
  652. }
  653. }
  654. Dictionary GDScriptWorkspace::generate_script_api(const String &p_path) {
  655. Dictionary api;
  656. const ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(p_path);
  657. if (parser) {
  658. api = parser->generate_api();
  659. }
  660. return api;
  661. }
  662. Error GDScriptWorkspace::resolve_signature(const LSP::TextDocumentPositionParams &p_doc_pos, LSP::SignatureHelp &r_signature) {
  663. const ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(get_file_path(p_doc_pos.textDocument.uri));
  664. if (parser) {
  665. LSP::TextDocumentPositionParams text_pos;
  666. text_pos.textDocument = p_doc_pos.textDocument;
  667. if (parser->get_left_function_call(p_doc_pos.position, text_pos.position, r_signature.activeParameter) == OK) {
  668. List<const LSP::DocumentSymbol *> symbols;
  669. if (const LSP::DocumentSymbol *symbol = resolve_symbol(text_pos)) {
  670. symbols.push_back(symbol);
  671. } else if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) {
  672. GDScriptLanguageProtocol::get_singleton()->resolve_related_symbols(text_pos, symbols);
  673. }
  674. for (const LSP::DocumentSymbol *const &symbol : symbols) {
  675. if (symbol->kind == LSP::SymbolKind::Method || symbol->kind == LSP::SymbolKind::Function) {
  676. LSP::SignatureInformation signature_info;
  677. signature_info.label = symbol->detail;
  678. signature_info.documentation = symbol->render();
  679. for (int i = 0; i < symbol->children.size(); i++) {
  680. const LSP::DocumentSymbol &arg = symbol->children[i];
  681. LSP::ParameterInformation arg_info;
  682. arg_info.label = arg.name;
  683. signature_info.parameters.push_back(arg_info);
  684. }
  685. r_signature.signatures.push_back(signature_info);
  686. break;
  687. }
  688. }
  689. if (r_signature.signatures.size()) {
  690. return OK;
  691. }
  692. }
  693. }
  694. return ERR_METHOD_NOT_FOUND;
  695. }
  696. GDScriptWorkspace::GDScriptWorkspace() {}
  697. GDScriptWorkspace::~GDScriptWorkspace() {}