gdscript_workspace.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  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()[0].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. dir->list_dir_begin();
  204. String file_name = dir->get_next();
  205. while (file_name.length()) {
  206. if (dir->current_is_dir() && file_name != "." && file_name != ".." && file_name != "./") {
  207. list_script_files(p_root_dir.path_join(file_name), r_files);
  208. } else if (file_name.ends_with(".gd")) {
  209. String script_file = p_root_dir.path_join(file_name);
  210. r_files.push_back(script_file);
  211. }
  212. file_name = dir->get_next();
  213. }
  214. }
  215. }
  216. ExtendGDScriptParser *GDScriptWorkspace::get_parse_successed_script(const String &p_path) {
  217. HashMap<String, ExtendGDScriptParser *>::Iterator S = scripts.find(p_path);
  218. if (!S) {
  219. parse_local_script(p_path);
  220. S = scripts.find(p_path);
  221. }
  222. if (S) {
  223. return S->value;
  224. }
  225. return nullptr;
  226. }
  227. ExtendGDScriptParser *GDScriptWorkspace::get_parse_result(const String &p_path) {
  228. HashMap<String, ExtendGDScriptParser *>::Iterator S = parse_results.find(p_path);
  229. if (!S) {
  230. parse_local_script(p_path);
  231. S = parse_results.find(p_path);
  232. }
  233. if (S) {
  234. return S->value;
  235. }
  236. return nullptr;
  237. }
  238. Error GDScriptWorkspace::initialize() {
  239. if (initialized) {
  240. return OK;
  241. }
  242. DocTools *doc = EditorHelp::get_doc_data();
  243. for (const KeyValue<String, DocData::ClassDoc> &E : doc->class_list) {
  244. const DocData::ClassDoc &class_data = E.value;
  245. lsp::DocumentSymbol class_symbol;
  246. String class_name = E.key;
  247. class_symbol.name = class_name;
  248. class_symbol.native_class = class_name;
  249. class_symbol.kind = lsp::SymbolKind::Class;
  250. class_symbol.detail = String("<Native> class ") + class_name;
  251. if (!class_data.inherits.is_empty()) {
  252. class_symbol.detail += " extends " + class_data.inherits;
  253. }
  254. class_symbol.documentation = class_data.brief_description + "\n" + class_data.description;
  255. for (int i = 0; i < class_data.constants.size(); i++) {
  256. const DocData::ConstantDoc &const_data = class_data.constants[i];
  257. lsp::DocumentSymbol symbol;
  258. symbol.name = const_data.name;
  259. symbol.native_class = class_name;
  260. symbol.kind = lsp::SymbolKind::Constant;
  261. symbol.detail = "const " + class_name + "." + const_data.name;
  262. if (const_data.enumeration.length()) {
  263. symbol.detail += ": " + const_data.enumeration;
  264. }
  265. symbol.detail += " = " + const_data.value;
  266. symbol.documentation = const_data.description;
  267. class_symbol.children.push_back(symbol);
  268. }
  269. for (int i = 0; i < class_data.properties.size(); i++) {
  270. const DocData::PropertyDoc &data = class_data.properties[i];
  271. lsp::DocumentSymbol symbol;
  272. symbol.name = data.name;
  273. symbol.native_class = class_name;
  274. symbol.kind = lsp::SymbolKind::Property;
  275. symbol.detail = "var " + class_name + "." + data.name;
  276. if (data.enumeration.length()) {
  277. symbol.detail += ": " + data.enumeration;
  278. } else {
  279. symbol.detail += ": " + data.type;
  280. }
  281. symbol.documentation = data.description;
  282. class_symbol.children.push_back(symbol);
  283. }
  284. for (int i = 0; i < class_data.theme_properties.size(); i++) {
  285. const DocData::ThemeItemDoc &data = class_data.theme_properties[i];
  286. lsp::DocumentSymbol symbol;
  287. symbol.name = data.name;
  288. symbol.native_class = class_name;
  289. symbol.kind = lsp::SymbolKind::Property;
  290. symbol.detail = "<Theme> var " + class_name + "." + data.name + ": " + data.type;
  291. symbol.documentation = data.description;
  292. class_symbol.children.push_back(symbol);
  293. }
  294. Vector<DocData::MethodDoc> methods_signals;
  295. methods_signals.append_array(class_data.constructors);
  296. methods_signals.append_array(class_data.methods);
  297. methods_signals.append_array(class_data.operators);
  298. const int signal_start_idx = methods_signals.size();
  299. methods_signals.append_array(class_data.signals);
  300. for (int i = 0; i < methods_signals.size(); i++) {
  301. const DocData::MethodDoc &data = methods_signals[i];
  302. lsp::DocumentSymbol symbol;
  303. symbol.name = data.name;
  304. symbol.native_class = class_name;
  305. symbol.kind = i >= signal_start_idx ? lsp::SymbolKind::Event : lsp::SymbolKind::Method;
  306. String params = "";
  307. bool arg_default_value_started = false;
  308. for (int j = 0; j < data.arguments.size(); j++) {
  309. const DocData::ArgumentDoc &arg = data.arguments[j];
  310. lsp::DocumentSymbol symbol_arg;
  311. symbol_arg.name = arg.name;
  312. symbol_arg.kind = lsp::SymbolKind::Variable;
  313. symbol_arg.detail = arg.type;
  314. if (!arg_default_value_started && !arg.default_value.is_empty()) {
  315. arg_default_value_started = true;
  316. }
  317. String arg_str = arg.name + ": " + arg.type;
  318. if (arg_default_value_started) {
  319. arg_str += " = " + arg.default_value;
  320. }
  321. if (j < data.arguments.size() - 1) {
  322. arg_str += ", ";
  323. }
  324. params += arg_str;
  325. symbol.children.push_back(symbol_arg);
  326. }
  327. if (data.qualifiers.contains("vararg")) {
  328. params += params.is_empty() ? "..." : ", ...";
  329. }
  330. String return_type = data.return_type;
  331. if (return_type.is_empty()) {
  332. return_type = "void";
  333. }
  334. symbol.detail = "func " + class_name + "." + data.name + "(" + params + ") -> " + return_type;
  335. symbol.documentation = data.description;
  336. class_symbol.children.push_back(symbol);
  337. }
  338. native_symbols.insert(class_name, class_symbol);
  339. }
  340. reload_all_workspace_scripts();
  341. if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) {
  342. for (const KeyValue<StringName, lsp::DocumentSymbol> &E : native_symbols) {
  343. ClassMembers members;
  344. const lsp::DocumentSymbol &class_symbol = E.value;
  345. for (int i = 0; i < class_symbol.children.size(); i++) {
  346. const lsp::DocumentSymbol &symbol = class_symbol.children[i];
  347. members.insert(symbol.name, &symbol);
  348. }
  349. native_members.insert(E.key, members);
  350. }
  351. // Cache member completions.
  352. for (const KeyValue<String, ExtendGDScriptParser *> &S : scripts) {
  353. S.value->get_member_completions();
  354. }
  355. }
  356. EditorNode *editor_node = EditorNode::get_singleton();
  357. editor_node->connect("script_add_function_request", callable_mp(this, &GDScriptWorkspace::apply_new_signal));
  358. return OK;
  359. }
  360. Error GDScriptWorkspace::parse_script(const String &p_path, const String &p_content) {
  361. ExtendGDScriptParser *parser = memnew(ExtendGDScriptParser);
  362. Error err = parser->parse(p_content, p_path);
  363. HashMap<String, ExtendGDScriptParser *>::Iterator last_parser = parse_results.find(p_path);
  364. HashMap<String, ExtendGDScriptParser *>::Iterator last_script = scripts.find(p_path);
  365. if (err == OK) {
  366. remove_cache_parser(p_path);
  367. parse_results[p_path] = parser;
  368. scripts[p_path] = parser;
  369. } else {
  370. if (last_parser && last_script && last_parser->value != last_script->value) {
  371. memdelete(last_parser->value);
  372. }
  373. parse_results[p_path] = parser;
  374. }
  375. publish_diagnostics(p_path);
  376. return err;
  377. }
  378. static bool is_valid_rename_target(const lsp::DocumentSymbol *p_symbol) {
  379. // Must be valid symbol.
  380. if (!p_symbol) {
  381. return false;
  382. }
  383. // Cannot rename builtin.
  384. if (!p_symbol->native_class.is_empty()) {
  385. return false;
  386. }
  387. // Source must be available.
  388. if (p_symbol->script_path.is_empty()) {
  389. return false;
  390. }
  391. return true;
  392. }
  393. Dictionary GDScriptWorkspace::rename(const lsp::TextDocumentPositionParams &p_doc_pos, const String &new_name) {
  394. lsp::WorkspaceEdit edit;
  395. const lsp::DocumentSymbol *reference_symbol = resolve_symbol(p_doc_pos);
  396. if (is_valid_rename_target(reference_symbol)) {
  397. Vector<lsp::Location> usages = find_all_usages(*reference_symbol);
  398. for (int i = 0; i < usages.size(); ++i) {
  399. lsp::Location loc = usages[i];
  400. edit.add_change(loc.uri, loc.range.start.line, loc.range.start.character, loc.range.end.character, new_name);
  401. }
  402. }
  403. return edit.to_json();
  404. }
  405. bool GDScriptWorkspace::can_rename(const lsp::TextDocumentPositionParams &p_doc_pos, lsp::DocumentSymbol &r_symbol, lsp::Range &r_range) {
  406. const lsp::DocumentSymbol *reference_symbol = resolve_symbol(p_doc_pos);
  407. if (!is_valid_rename_target(reference_symbol)) {
  408. return false;
  409. }
  410. String path = get_file_path(p_doc_pos.textDocument.uri);
  411. if (const ExtendGDScriptParser *parser = get_parse_result(path)) {
  412. parser->get_identifier_under_position(p_doc_pos.position, r_range);
  413. r_symbol = *reference_symbol;
  414. return true;
  415. }
  416. return false;
  417. }
  418. Vector<lsp::Location> GDScriptWorkspace::find_usages_in_file(const lsp::DocumentSymbol &p_symbol, const String &p_file_path) {
  419. Vector<lsp::Location> usages;
  420. String identifier = p_symbol.name;
  421. if (const ExtendGDScriptParser *parser = get_parse_result(p_file_path)) {
  422. const PackedStringArray &content = parser->get_lines();
  423. for (int i = 0; i < content.size(); ++i) {
  424. String line = content[i];
  425. int character = line.find(identifier);
  426. while (character > -1) {
  427. lsp::TextDocumentPositionParams params;
  428. lsp::TextDocumentIdentifier text_doc;
  429. text_doc.uri = get_file_uri(p_file_path);
  430. params.textDocument = text_doc;
  431. params.position.line = i;
  432. params.position.character = character;
  433. const lsp::DocumentSymbol *other_symbol = resolve_symbol(params);
  434. if (other_symbol == &p_symbol) {
  435. lsp::Location loc;
  436. loc.uri = text_doc.uri;
  437. loc.range.start = params.position;
  438. loc.range.end.line = params.position.line;
  439. loc.range.end.character = params.position.character + identifier.length();
  440. usages.append(loc);
  441. }
  442. character = line.find(identifier, character + 1);
  443. }
  444. }
  445. }
  446. return usages;
  447. }
  448. Vector<lsp::Location> GDScriptWorkspace::find_all_usages(const lsp::DocumentSymbol &p_symbol) {
  449. if (p_symbol.local) {
  450. // Only search in current document.
  451. return find_usages_in_file(p_symbol, p_symbol.script_path);
  452. }
  453. // Search in all documents.
  454. List<String> paths;
  455. list_script_files("res://", paths);
  456. Vector<lsp::Location> usages;
  457. for (List<String>::Element *PE = paths.front(); PE; PE = PE->next()) {
  458. usages.append_array(find_usages_in_file(p_symbol, PE->get()));
  459. }
  460. return usages;
  461. }
  462. Error GDScriptWorkspace::parse_local_script(const String &p_path) {
  463. Error err;
  464. String content = FileAccess::get_file_as_string(p_path, &err);
  465. if (err == OK) {
  466. err = parse_script(p_path, content);
  467. }
  468. return err;
  469. }
  470. String GDScriptWorkspace::get_file_path(const String &p_uri) const {
  471. String path = p_uri.uri_decode();
  472. String base_uri = root_uri.uri_decode();
  473. path = path.replacen(base_uri + "/", "res://");
  474. return path;
  475. }
  476. String GDScriptWorkspace::get_file_uri(const String &p_path) const {
  477. String uri = p_path;
  478. uri = uri.replace("res://", root_uri + "/");
  479. return uri;
  480. }
  481. void GDScriptWorkspace::publish_diagnostics(const String &p_path) {
  482. Dictionary params;
  483. Array errors;
  484. HashMap<String, ExtendGDScriptParser *>::ConstIterator ele = parse_results.find(p_path);
  485. if (ele) {
  486. const Vector<lsp::Diagnostic> &list = ele->value->get_diagnostics();
  487. errors.resize(list.size());
  488. for (int i = 0; i < list.size(); ++i) {
  489. errors[i] = list[i].to_json();
  490. }
  491. }
  492. params["diagnostics"] = errors;
  493. params["uri"] = get_file_uri(p_path);
  494. GDScriptLanguageProtocol::get_singleton()->notify_client("textDocument/publishDiagnostics", params);
  495. }
  496. void GDScriptWorkspace::_get_owners(EditorFileSystemDirectory *efsd, String p_path, List<String> &owners) {
  497. if (!efsd) {
  498. return;
  499. }
  500. for (int i = 0; i < efsd->get_subdir_count(); i++) {
  501. _get_owners(efsd->get_subdir(i), p_path, owners);
  502. }
  503. for (int i = 0; i < efsd->get_file_count(); i++) {
  504. Vector<String> deps = efsd->get_file_deps(i);
  505. bool found = false;
  506. for (int j = 0; j < deps.size(); j++) {
  507. if (deps[j] == p_path) {
  508. found = true;
  509. break;
  510. }
  511. }
  512. if (!found) {
  513. continue;
  514. }
  515. owners.push_back(efsd->get_file_path(i));
  516. }
  517. }
  518. Node *GDScriptWorkspace::_get_owner_scene_node(String p_path) {
  519. Node *owner_scene_node = nullptr;
  520. List<String> owners;
  521. _get_owners(EditorFileSystem::get_singleton()->get_filesystem(), p_path, owners);
  522. for (int i = 0; i < owners.size(); i++) {
  523. NodePath owner_path = owners[i];
  524. Ref<Resource> owner_res = ResourceLoader::load(owner_path);
  525. if (Object::cast_to<PackedScene>(owner_res.ptr())) {
  526. Ref<PackedScene> owner_packed_scene = Ref<PackedScene>(Object::cast_to<PackedScene>(*owner_res));
  527. owner_scene_node = owner_packed_scene->instantiate();
  528. break;
  529. }
  530. }
  531. return owner_scene_node;
  532. }
  533. void GDScriptWorkspace::completion(const lsp::CompletionParams &p_params, List<ScriptLanguage::CodeCompletionOption> *r_options) {
  534. String path = get_file_path(p_params.textDocument.uri);
  535. String call_hint;
  536. bool forced = false;
  537. if (const ExtendGDScriptParser *parser = get_parse_result(path)) {
  538. Node *owner_scene_node = _get_owner_scene_node(path);
  539. Array stack;
  540. Node *current = nullptr;
  541. if (owner_scene_node != nullptr) {
  542. stack.push_back(owner_scene_node);
  543. while (!stack.is_empty()) {
  544. current = Object::cast_to<Node>(stack.pop_back());
  545. Ref<GDScript> scr = current->get_script();
  546. if (scr.is_valid() && scr->get_path() == path) {
  547. break;
  548. }
  549. for (int i = 0; i < current->get_child_count(); ++i) {
  550. stack.push_back(current->get_child(i));
  551. }
  552. }
  553. Ref<GDScript> scr = current->get_script();
  554. if (!scr.is_valid() || scr->get_path() != path) {
  555. current = owner_scene_node;
  556. }
  557. }
  558. String code = parser->get_text_for_completion(p_params.position);
  559. GDScriptLanguage::get_singleton()->complete_code(code, path, current, r_options, forced, call_hint);
  560. if (owner_scene_node) {
  561. memdelete(owner_scene_node);
  562. }
  563. }
  564. }
  565. const lsp::DocumentSymbol *GDScriptWorkspace::resolve_symbol(const lsp::TextDocumentPositionParams &p_doc_pos, const String &p_symbol_name, bool p_func_required) {
  566. const lsp::DocumentSymbol *symbol = nullptr;
  567. String path = get_file_path(p_doc_pos.textDocument.uri);
  568. if (const ExtendGDScriptParser *parser = get_parse_result(path)) {
  569. String symbol_identifier = p_symbol_name;
  570. Vector<String> identifier_parts = symbol_identifier.split("(");
  571. if (identifier_parts.size()) {
  572. symbol_identifier = identifier_parts[0];
  573. }
  574. lsp::Position pos = p_doc_pos.position;
  575. if (symbol_identifier.is_empty()) {
  576. lsp::Range range;
  577. symbol_identifier = parser->get_identifier_under_position(p_doc_pos.position, range);
  578. pos.character = range.end.character;
  579. }
  580. if (!symbol_identifier.is_empty()) {
  581. if (ScriptServer::is_global_class(symbol_identifier)) {
  582. String class_path = ScriptServer::get_global_class_path(symbol_identifier);
  583. symbol = get_script_symbol(class_path);
  584. } else {
  585. ScriptLanguage::LookupResult ret;
  586. if (symbol_identifier == "new" && parser->get_lines()[p_doc_pos.position.line].replace(" ", "").replace("\t", "").find("new(") > -1) {
  587. symbol_identifier = "_init";
  588. }
  589. if (OK == GDScriptLanguage::get_singleton()->lookup_code(parser->get_text_for_lookup_symbol(pos, symbol_identifier, p_func_required), symbol_identifier, path, nullptr, ret)) {
  590. if (ret.type == ScriptLanguage::LOOKUP_RESULT_SCRIPT_LOCATION) {
  591. String target_script_path = path;
  592. if (!ret.script.is_null()) {
  593. target_script_path = ret.script->get_path();
  594. } else if (!ret.class_path.is_empty()) {
  595. target_script_path = ret.class_path;
  596. }
  597. if (const ExtendGDScriptParser *target_parser = get_parse_result(target_script_path)) {
  598. symbol = target_parser->get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(ret.location), symbol_identifier);
  599. if (symbol) {
  600. switch (symbol->kind) {
  601. case lsp::SymbolKind::Function: {
  602. if (symbol->name != symbol_identifier) {
  603. symbol = get_parameter_symbol(symbol, symbol_identifier);
  604. }
  605. } break;
  606. }
  607. }
  608. }
  609. } else {
  610. String member = ret.class_member;
  611. if (member.is_empty() && symbol_identifier != ret.class_name) {
  612. member = symbol_identifier;
  613. }
  614. symbol = get_native_symbol(ret.class_name, member);
  615. }
  616. } else {
  617. symbol = get_local_symbol_at(parser, symbol_identifier, p_doc_pos.position);
  618. if (!symbol) {
  619. symbol = parser->get_member_symbol(symbol_identifier);
  620. }
  621. }
  622. }
  623. }
  624. }
  625. return symbol;
  626. }
  627. void GDScriptWorkspace::resolve_related_symbols(const lsp::TextDocumentPositionParams &p_doc_pos, List<const lsp::DocumentSymbol *> &r_list) {
  628. String path = get_file_path(p_doc_pos.textDocument.uri);
  629. if (const ExtendGDScriptParser *parser = get_parse_result(path)) {
  630. String symbol_identifier;
  631. lsp::Range range;
  632. symbol_identifier = parser->get_identifier_under_position(p_doc_pos.position, range);
  633. for (const KeyValue<StringName, ClassMembers> &E : native_members) {
  634. const ClassMembers &members = native_members.get(E.key);
  635. if (const lsp::DocumentSymbol *const *symbol = members.getptr(symbol_identifier)) {
  636. r_list.push_back(*symbol);
  637. }
  638. }
  639. for (const KeyValue<String, ExtendGDScriptParser *> &E : scripts) {
  640. const ExtendGDScriptParser *scr = E.value;
  641. const ClassMembers &members = scr->get_members();
  642. if (const lsp::DocumentSymbol *const *symbol = members.getptr(symbol_identifier)) {
  643. r_list.push_back(*symbol);
  644. }
  645. for (const KeyValue<String, ClassMembers> &F : scr->get_inner_classes()) {
  646. const ClassMembers *inner_class = &F.value;
  647. if (const lsp::DocumentSymbol *const *symbol = inner_class->getptr(symbol_identifier)) {
  648. r_list.push_back(*symbol);
  649. }
  650. }
  651. }
  652. }
  653. }
  654. const lsp::DocumentSymbol *GDScriptWorkspace::resolve_native_symbol(const lsp::NativeSymbolInspectParams &p_params) {
  655. if (HashMap<StringName, lsp::DocumentSymbol>::Iterator E = native_symbols.find(p_params.native_class)) {
  656. const lsp::DocumentSymbol &symbol = E->value;
  657. if (p_params.symbol_name.is_empty() || p_params.symbol_name == symbol.name) {
  658. return &symbol;
  659. }
  660. for (int i = 0; i < symbol.children.size(); ++i) {
  661. if (symbol.children[i].name == p_params.symbol_name) {
  662. return &(symbol.children[i]);
  663. }
  664. }
  665. }
  666. return nullptr;
  667. }
  668. void GDScriptWorkspace::resolve_document_links(const String &p_uri, List<lsp::DocumentLink> &r_list) {
  669. if (const ExtendGDScriptParser *parser = get_parse_successed_script(get_file_path(p_uri))) {
  670. const List<lsp::DocumentLink> &links = parser->get_document_links();
  671. for (const lsp::DocumentLink &E : links) {
  672. r_list.push_back(E);
  673. }
  674. }
  675. }
  676. Dictionary GDScriptWorkspace::generate_script_api(const String &p_path) {
  677. Dictionary api;
  678. if (const ExtendGDScriptParser *parser = get_parse_successed_script(p_path)) {
  679. api = parser->generate_api();
  680. }
  681. return api;
  682. }
  683. Error GDScriptWorkspace::resolve_signature(const lsp::TextDocumentPositionParams &p_doc_pos, lsp::SignatureHelp &r_signature) {
  684. if (const ExtendGDScriptParser *parser = get_parse_result(get_file_path(p_doc_pos.textDocument.uri))) {
  685. lsp::TextDocumentPositionParams text_pos;
  686. text_pos.textDocument = p_doc_pos.textDocument;
  687. if (parser->get_left_function_call(p_doc_pos.position, text_pos.position, r_signature.activeParameter) == OK) {
  688. List<const lsp::DocumentSymbol *> symbols;
  689. if (const lsp::DocumentSymbol *symbol = resolve_symbol(text_pos)) {
  690. symbols.push_back(symbol);
  691. } else if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) {
  692. GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_related_symbols(text_pos, symbols);
  693. }
  694. for (const lsp::DocumentSymbol *const &symbol : symbols) {
  695. if (symbol->kind == lsp::SymbolKind::Method || symbol->kind == lsp::SymbolKind::Function) {
  696. lsp::SignatureInformation signature_info;
  697. signature_info.label = symbol->detail;
  698. signature_info.documentation = symbol->render();
  699. for (int i = 0; i < symbol->children.size(); i++) {
  700. const lsp::DocumentSymbol &arg = symbol->children[i];
  701. lsp::ParameterInformation arg_info;
  702. arg_info.label = arg.name;
  703. signature_info.parameters.push_back(arg_info);
  704. }
  705. r_signature.signatures.push_back(signature_info);
  706. break;
  707. }
  708. }
  709. if (r_signature.signatures.size()) {
  710. return OK;
  711. }
  712. }
  713. }
  714. return ERR_METHOD_NOT_FOUND;
  715. }
  716. GDScriptWorkspace::GDScriptWorkspace() {
  717. ProjectSettings::get_singleton()->get_resource_path();
  718. }
  719. GDScriptWorkspace::~GDScriptWorkspace() {
  720. HashSet<String> cached_parsers;
  721. for (const KeyValue<String, ExtendGDScriptParser *> &E : parse_results) {
  722. cached_parsers.insert(E.key);
  723. }
  724. for (const KeyValue<String, ExtendGDScriptParser *> &E : scripts) {
  725. cached_parsers.insert(E.key);
  726. }
  727. for (const String &E : cached_parsers) {
  728. remove_cache_parser(E);
  729. }
  730. }