gdscript_workspace.cpp 28 KB

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