gdscript_workspace.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  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("didDeleteFiles"), &GDScriptWorkspace::didDeleteFiles);
  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::didDeleteFiles(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. // Might contain pseudo classes like @GDScript that only exist in documentation.
  139. if (ClassDB::class_exists(class_name)) {
  140. class_name = ClassDB::get_parent_class(class_name);
  141. } else {
  142. break;
  143. }
  144. }
  145. return nullptr;
  146. }
  147. const LSP::DocumentSymbol *GDScriptWorkspace::get_script_symbol(const String &p_path) const {
  148. HashMap<String, ExtendGDScriptParser *>::ConstIterator S = scripts.find(p_path);
  149. if (S) {
  150. return &(S->value->get_symbols());
  151. }
  152. return nullptr;
  153. }
  154. const LSP::DocumentSymbol *GDScriptWorkspace::get_parameter_symbol(const LSP::DocumentSymbol *p_parent, const String &symbol_identifier) {
  155. for (int i = 0; i < p_parent->children.size(); ++i) {
  156. const LSP::DocumentSymbol *parameter_symbol = &p_parent->children[i];
  157. if (!parameter_symbol->detail.is_empty() && parameter_symbol->name == symbol_identifier) {
  158. return parameter_symbol;
  159. }
  160. }
  161. return nullptr;
  162. }
  163. const LSP::DocumentSymbol *GDScriptWorkspace::get_local_symbol_at(const ExtendGDScriptParser *p_parser, const String &p_symbol_identifier, const LSP::Position p_position) {
  164. // Go down and pick closest `DocumentSymbol` with `p_symbol_identifier`.
  165. const LSP::DocumentSymbol *current = &p_parser->get_symbols();
  166. const LSP::DocumentSymbol *best_match = nullptr;
  167. while (current) {
  168. if (current->name == p_symbol_identifier) {
  169. if (current->selectionRange.contains(p_position)) {
  170. // Exact match: pos is ON symbol decl identifier.
  171. return current;
  172. }
  173. best_match = current;
  174. }
  175. const LSP::DocumentSymbol *parent = current;
  176. current = nullptr;
  177. for (const LSP::DocumentSymbol &child : parent->children) {
  178. if (child.range.contains(p_position)) {
  179. current = &child;
  180. break;
  181. }
  182. }
  183. }
  184. return best_match;
  185. }
  186. void GDScriptWorkspace::reload_all_workspace_scripts() {
  187. List<String> paths;
  188. list_script_files("res://", paths);
  189. for (const String &path : paths) {
  190. Error err;
  191. String content = FileAccess::get_file_as_string(path, &err);
  192. ERR_CONTINUE(err != OK);
  193. err = parse_script(path, content);
  194. if (err != OK) {
  195. HashMap<String, ExtendGDScriptParser *>::Iterator S = parse_results.find(path);
  196. String err_msg = "Failed parse script " + path;
  197. if (S) {
  198. err_msg += "\n" + S->value->get_errors().front()->get().message;
  199. }
  200. ERR_CONTINUE_MSG(err != OK, err_msg);
  201. }
  202. }
  203. }
  204. void GDScriptWorkspace::list_script_files(const String &p_root_dir, List<String> &r_files) {
  205. Error err;
  206. Ref<DirAccess> dir = DirAccess::open(p_root_dir, &err);
  207. if (OK != err) {
  208. return;
  209. }
  210. // Ignore scripts in directories with a .gdignore file.
  211. if (dir->file_exists(".gdignore")) {
  212. return;
  213. }
  214. dir->list_dir_begin();
  215. String file_name = dir->get_next();
  216. while (file_name.length()) {
  217. if (dir->current_is_dir() && file_name != "." && file_name != ".." && file_name != "./") {
  218. list_script_files(p_root_dir.path_join(file_name), r_files);
  219. } else if (file_name.ends_with(".gd")) {
  220. String script_file = p_root_dir.path_join(file_name);
  221. r_files.push_back(script_file);
  222. }
  223. file_name = dir->get_next();
  224. }
  225. }
  226. ExtendGDScriptParser *GDScriptWorkspace::get_parse_successed_script(const String &p_path) {
  227. HashMap<String, ExtendGDScriptParser *>::Iterator S = scripts.find(p_path);
  228. if (!S) {
  229. parse_local_script(p_path);
  230. S = scripts.find(p_path);
  231. }
  232. if (S) {
  233. return S->value;
  234. }
  235. return nullptr;
  236. }
  237. ExtendGDScriptParser *GDScriptWorkspace::get_parse_result(const String &p_path) {
  238. HashMap<String, ExtendGDScriptParser *>::Iterator S = parse_results.find(p_path);
  239. if (!S) {
  240. parse_local_script(p_path);
  241. S = parse_results.find(p_path);
  242. }
  243. if (S) {
  244. return S->value;
  245. }
  246. return nullptr;
  247. }
  248. #define HANDLE_DOC(m_string) ((is_native ? DTR(m_string) : (m_string)).strip_edges())
  249. Error GDScriptWorkspace::initialize() {
  250. if (initialized) {
  251. return OK;
  252. }
  253. DocTools *doc = EditorHelp::get_doc_data();
  254. for (const KeyValue<String, DocData::ClassDoc> &E : doc->class_list) {
  255. const DocData::ClassDoc &class_data = E.value;
  256. const bool is_native = !class_data.is_script_doc;
  257. LSP::DocumentSymbol class_symbol;
  258. String class_name = E.key;
  259. class_symbol.name = class_name;
  260. class_symbol.native_class = class_name;
  261. class_symbol.kind = LSP::SymbolKind::Class;
  262. class_symbol.detail = String("<Native> class ") + class_name;
  263. if (!class_data.inherits.is_empty()) {
  264. class_symbol.detail += " extends " + class_data.inherits;
  265. }
  266. class_symbol.documentation = HANDLE_DOC(class_data.brief_description) + "\n" + HANDLE_DOC(class_data.description);
  267. for (int i = 0; i < class_data.constants.size(); i++) {
  268. const DocData::ConstantDoc &const_data = class_data.constants[i];
  269. LSP::DocumentSymbol symbol;
  270. symbol.name = const_data.name;
  271. symbol.native_class = class_name;
  272. symbol.kind = LSP::SymbolKind::Constant;
  273. symbol.detail = "const " + class_name + "." + const_data.name;
  274. if (const_data.enumeration.length()) {
  275. symbol.detail += ": " + const_data.enumeration;
  276. }
  277. symbol.detail += " = " + const_data.value;
  278. symbol.documentation = HANDLE_DOC(const_data.description);
  279. class_symbol.children.push_back(symbol);
  280. }
  281. for (int i = 0; i < class_data.properties.size(); i++) {
  282. const DocData::PropertyDoc &data = class_data.properties[i];
  283. LSP::DocumentSymbol symbol;
  284. symbol.name = data.name;
  285. symbol.native_class = class_name;
  286. symbol.kind = LSP::SymbolKind::Property;
  287. symbol.detail = "var " + class_name + "." + data.name;
  288. if (data.enumeration.length()) {
  289. symbol.detail += ": " + data.enumeration;
  290. } else {
  291. symbol.detail += ": " + data.type;
  292. }
  293. symbol.documentation = HANDLE_DOC(data.description);
  294. class_symbol.children.push_back(symbol);
  295. }
  296. for (int i = 0; i < class_data.theme_properties.size(); i++) {
  297. const DocData::ThemeItemDoc &data = class_data.theme_properties[i];
  298. LSP::DocumentSymbol symbol;
  299. symbol.name = data.name;
  300. symbol.native_class = class_name;
  301. symbol.kind = LSP::SymbolKind::Property;
  302. symbol.detail = "<Theme> var " + class_name + "." + data.name + ": " + data.type;
  303. symbol.documentation = HANDLE_DOC(data.description);
  304. class_symbol.children.push_back(symbol);
  305. }
  306. Vector<DocData::MethodDoc> method_likes;
  307. method_likes.append_array(class_data.methods);
  308. method_likes.append_array(class_data.annotations);
  309. const int constructors_start_idx = method_likes.size();
  310. method_likes.append_array(class_data.constructors);
  311. const int operator_start_idx = method_likes.size();
  312. method_likes.append_array(class_data.operators);
  313. const int signal_start_idx = method_likes.size();
  314. method_likes.append_array(class_data.signals);
  315. for (int i = 0; i < method_likes.size(); i++) {
  316. const DocData::MethodDoc &data = method_likes[i];
  317. LSP::DocumentSymbol symbol;
  318. symbol.name = data.name;
  319. symbol.native_class = class_name;
  320. if (i >= signal_start_idx) {
  321. symbol.kind = LSP::SymbolKind::Event;
  322. } else if (i >= operator_start_idx) {
  323. symbol.kind = LSP::SymbolKind::Operator;
  324. } else if (i >= constructors_start_idx) {
  325. symbol.kind = LSP::SymbolKind::Constructor;
  326. } else {
  327. symbol.kind = LSP::SymbolKind::Method;
  328. }
  329. String params = "";
  330. bool arg_default_value_started = false;
  331. for (int j = 0; j < data.arguments.size(); j++) {
  332. const DocData::ArgumentDoc &arg = data.arguments[j];
  333. LSP::DocumentSymbol symbol_arg;
  334. symbol_arg.name = arg.name;
  335. symbol_arg.kind = LSP::SymbolKind::Variable;
  336. symbol_arg.detail = arg.type;
  337. if (!arg_default_value_started && !arg.default_value.is_empty()) {
  338. arg_default_value_started = true;
  339. }
  340. String arg_str = arg.name + ": " + arg.type;
  341. if (arg_default_value_started) {
  342. arg_str += " = " + arg.default_value;
  343. }
  344. if (j < data.arguments.size() - 1) {
  345. arg_str += ", ";
  346. }
  347. params += arg_str;
  348. symbol.children.push_back(symbol_arg);
  349. }
  350. if (data.qualifiers.contains("vararg")) {
  351. params += params.is_empty() ? "..." : ", ...";
  352. }
  353. String return_type = data.return_type;
  354. if (return_type.is_empty()) {
  355. return_type = "void";
  356. }
  357. symbol.detail = "func " + class_name + "." + data.name + "(" + params + ") -> " + return_type;
  358. symbol.documentation = HANDLE_DOC(data.description);
  359. class_symbol.children.push_back(symbol);
  360. }
  361. native_symbols.insert(class_name, class_symbol);
  362. }
  363. reload_all_workspace_scripts();
  364. if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) {
  365. for (const KeyValue<StringName, LSP::DocumentSymbol> &E : native_symbols) {
  366. ClassMembers members;
  367. const LSP::DocumentSymbol &class_symbol = E.value;
  368. for (int i = 0; i < class_symbol.children.size(); i++) {
  369. const LSP::DocumentSymbol &symbol = class_symbol.children[i];
  370. members.insert(symbol.name, &symbol);
  371. }
  372. native_members.insert(E.key, members);
  373. }
  374. // Cache member completions.
  375. for (const KeyValue<String, ExtendGDScriptParser *> &S : scripts) {
  376. S.value->get_member_completions();
  377. }
  378. }
  379. EditorNode *editor_node = EditorNode::get_singleton();
  380. editor_node->connect("script_add_function_request", callable_mp(this, &GDScriptWorkspace::apply_new_signal));
  381. return OK;
  382. }
  383. Error GDScriptWorkspace::parse_script(const String &p_path, const String &p_content) {
  384. ExtendGDScriptParser *parser = memnew(ExtendGDScriptParser);
  385. Error err = parser->parse(p_content, p_path);
  386. HashMap<String, ExtendGDScriptParser *>::Iterator last_parser = parse_results.find(p_path);
  387. HashMap<String, ExtendGDScriptParser *>::Iterator last_script = scripts.find(p_path);
  388. if (err == OK) {
  389. remove_cache_parser(p_path);
  390. parse_results[p_path] = parser;
  391. scripts[p_path] = parser;
  392. } else {
  393. if (last_parser && last_script && last_parser->value != last_script->value) {
  394. memdelete(last_parser->value);
  395. }
  396. parse_results[p_path] = parser;
  397. }
  398. publish_diagnostics(p_path);
  399. return err;
  400. }
  401. static bool is_valid_rename_target(const LSP::DocumentSymbol *p_symbol) {
  402. // Must be valid symbol.
  403. if (!p_symbol) {
  404. return false;
  405. }
  406. // Cannot rename builtin.
  407. if (!p_symbol->native_class.is_empty()) {
  408. return false;
  409. }
  410. // Source must be available.
  411. if (p_symbol->script_path.is_empty()) {
  412. return false;
  413. }
  414. return true;
  415. }
  416. Dictionary GDScriptWorkspace::rename(const LSP::TextDocumentPositionParams &p_doc_pos, const String &new_name) {
  417. LSP::WorkspaceEdit edit;
  418. const LSP::DocumentSymbol *reference_symbol = resolve_symbol(p_doc_pos);
  419. if (is_valid_rename_target(reference_symbol)) {
  420. Vector<LSP::Location> usages = find_all_usages(*reference_symbol);
  421. for (int i = 0; i < usages.size(); ++i) {
  422. LSP::Location loc = usages[i];
  423. edit.add_change(loc.uri, loc.range.start.line, loc.range.start.character, loc.range.end.character, new_name);
  424. }
  425. }
  426. return edit.to_json();
  427. }
  428. bool GDScriptWorkspace::can_rename(const LSP::TextDocumentPositionParams &p_doc_pos, LSP::DocumentSymbol &r_symbol, LSP::Range &r_range) {
  429. const LSP::DocumentSymbol *reference_symbol = resolve_symbol(p_doc_pos);
  430. if (!is_valid_rename_target(reference_symbol)) {
  431. return false;
  432. }
  433. String path = get_file_path(p_doc_pos.textDocument.uri);
  434. if (const ExtendGDScriptParser *parser = get_parse_result(path)) {
  435. // We only care about the range.
  436. _ALLOW_DISCARD_ parser->get_identifier_under_position(p_doc_pos.position, r_range);
  437. r_symbol = *reference_symbol;
  438. return true;
  439. }
  440. return false;
  441. }
  442. Vector<LSP::Location> GDScriptWorkspace::find_usages_in_file(const LSP::DocumentSymbol &p_symbol, const String &p_file_path) {
  443. Vector<LSP::Location> usages;
  444. String identifier = p_symbol.name;
  445. if (const ExtendGDScriptParser *parser = get_parse_result(p_file_path)) {
  446. const PackedStringArray &content = parser->get_lines();
  447. for (int i = 0; i < content.size(); ++i) {
  448. String line = content[i];
  449. int character = line.find(identifier);
  450. while (character > -1) {
  451. LSP::TextDocumentPositionParams params;
  452. LSP::TextDocumentIdentifier text_doc;
  453. text_doc.uri = get_file_uri(p_file_path);
  454. params.textDocument = text_doc;
  455. params.position.line = i;
  456. params.position.character = character;
  457. const LSP::DocumentSymbol *other_symbol = resolve_symbol(params);
  458. if (other_symbol == &p_symbol) {
  459. LSP::Location loc;
  460. loc.uri = text_doc.uri;
  461. loc.range.start = params.position;
  462. loc.range.end.line = params.position.line;
  463. loc.range.end.character = params.position.character + identifier.length();
  464. usages.append(loc);
  465. }
  466. character = line.find(identifier, character + 1);
  467. }
  468. }
  469. }
  470. return usages;
  471. }
  472. Vector<LSP::Location> GDScriptWorkspace::find_all_usages(const LSP::DocumentSymbol &p_symbol) {
  473. if (p_symbol.local) {
  474. // Only search in current document.
  475. return find_usages_in_file(p_symbol, p_symbol.script_path);
  476. }
  477. // Search in all documents.
  478. List<String> paths;
  479. list_script_files("res://", paths);
  480. Vector<LSP::Location> usages;
  481. for (const String &path : paths) {
  482. usages.append_array(find_usages_in_file(p_symbol, path));
  483. }
  484. return usages;
  485. }
  486. Error GDScriptWorkspace::parse_local_script(const String &p_path) {
  487. Error err;
  488. String content = FileAccess::get_file_as_string(p_path, &err);
  489. if (err == OK) {
  490. err = parse_script(p_path, content);
  491. }
  492. return err;
  493. }
  494. String GDScriptWorkspace::get_file_path(const String &p_uri) {
  495. int port;
  496. String scheme;
  497. String host;
  498. String encoded_path;
  499. String fragment;
  500. // Don't use the returned error, the result isn't OK for URIs that are not valid web URLs.
  501. p_uri.parse_url(scheme, host, port, encoded_path, fragment);
  502. // TODO: Make the parsing RFC-3986 compliant.
  503. ERR_FAIL_COND_V_MSG(scheme != "file" && scheme != "file:" && scheme != "file://", String(), "LSP: The language server only supports the file protocol: " + p_uri);
  504. // Treat host like authority for now and ignore the port. It's an edge case for invalid file URI's anyway.
  505. ERR_FAIL_COND_V_MSG(host != "" && host != "localhost", String(), "LSP: The language server does not support nonlocal files: " + p_uri);
  506. // If query or fragment are present, the URI is not a valid file URI as per RFC-8089.
  507. // We currently don't handle the query and it will be part of the path. However,
  508. // this should not be a problem for a correct file URI.
  509. ERR_FAIL_COND_V_MSG(fragment != "", String(), "LSP: Received malformed file URI: " + p_uri);
  510. String canonical_res = ProjectSettings::get_singleton()->get_resource_path();
  511. String simple_path = encoded_path.uri_file_decode().simplify_path();
  512. // First try known paths that point to res://, to reduce file system interaction.
  513. bool res_adjusted = false;
  514. for (const String &res_path : absolute_res_paths) {
  515. if (simple_path.begins_with(res_path)) {
  516. res_adjusted = true;
  517. simple_path = "res://" + simple_path.substr(res_path.size());
  518. break;
  519. }
  520. }
  521. // Traverse the path and compare each directory with res://
  522. if (!res_adjusted) {
  523. Ref<DirAccess> dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  524. int offset = 0;
  525. while (offset <= simple_path.length()) {
  526. offset = simple_path.find_char('/', offset);
  527. if (offset == -1) {
  528. offset = simple_path.length();
  529. }
  530. String part = simple_path.substr(0, offset);
  531. if (!part.is_empty()) {
  532. bool is_equal = dir->is_equivalent(canonical_res, part);
  533. if (is_equal) {
  534. absolute_res_paths.insert(part);
  535. res_adjusted = true;
  536. simple_path = "res://" + simple_path.substr(offset + 1);
  537. break;
  538. }
  539. }
  540. offset += 1;
  541. }
  542. // Could not resolve the path to the project.
  543. if (!res_adjusted) {
  544. return simple_path;
  545. }
  546. }
  547. // Resolve the file inside of the project using EditorFileSystem.
  548. EditorFileSystemDirectory *editor_dir;
  549. int file_idx;
  550. editor_dir = EditorFileSystem::get_singleton()->find_file(simple_path, &file_idx);
  551. if (editor_dir) {
  552. return editor_dir->get_file_path(file_idx);
  553. }
  554. return simple_path;
  555. }
  556. String GDScriptWorkspace::get_file_uri(const String &p_path) const {
  557. String path = ProjectSettings::get_singleton()->globalize_path(p_path).lstrip("/");
  558. LocalVector<String> encoded_parts;
  559. for (const String &part : path.split("/")) {
  560. encoded_parts.push_back(part.uri_encode());
  561. }
  562. // Always return file URI's with authority part (encoding drive letters with leading slash), to maintain compat with RFC-1738 which required it.
  563. return "file:///" + String("/").join(encoded_parts);
  564. }
  565. void GDScriptWorkspace::publish_diagnostics(const String &p_path) {
  566. Dictionary params;
  567. Array errors;
  568. HashMap<String, ExtendGDScriptParser *>::ConstIterator ele = parse_results.find(p_path);
  569. if (ele) {
  570. const Vector<LSP::Diagnostic> &list = ele->value->get_diagnostics();
  571. errors.resize(list.size());
  572. for (int i = 0; i < list.size(); ++i) {
  573. errors[i] = list[i].to_json();
  574. }
  575. }
  576. params["diagnostics"] = errors;
  577. params["uri"] = get_file_uri(p_path);
  578. GDScriptLanguageProtocol::get_singleton()->notify_client("textDocument/publishDiagnostics", params);
  579. }
  580. void GDScriptWorkspace::_get_owners(EditorFileSystemDirectory *efsd, String p_path, List<String> &owners) {
  581. if (!efsd) {
  582. return;
  583. }
  584. for (int i = 0; i < efsd->get_subdir_count(); i++) {
  585. _get_owners(efsd->get_subdir(i), p_path, owners);
  586. }
  587. for (int i = 0; i < efsd->get_file_count(); i++) {
  588. Vector<String> deps = efsd->get_file_deps(i);
  589. bool found = false;
  590. for (int j = 0; j < deps.size(); j++) {
  591. if (deps[j] == p_path) {
  592. found = true;
  593. break;
  594. }
  595. }
  596. if (!found) {
  597. continue;
  598. }
  599. owners.push_back(efsd->get_file_path(i));
  600. }
  601. }
  602. Node *GDScriptWorkspace::_get_owner_scene_node(String p_path) {
  603. Node *owner_scene_node = nullptr;
  604. List<String> owners;
  605. _get_owners(EditorFileSystem::get_singleton()->get_filesystem(), p_path, owners);
  606. for (const String &owner : owners) {
  607. NodePath owner_path = owner;
  608. Ref<Resource> owner_res = ResourceLoader::load(String(owner_path));
  609. if (Object::cast_to<PackedScene>(owner_res.ptr())) {
  610. Ref<PackedScene> owner_packed_scene = Ref<PackedScene>(Object::cast_to<PackedScene>(*owner_res));
  611. owner_scene_node = owner_packed_scene->instantiate();
  612. break;
  613. }
  614. }
  615. return owner_scene_node;
  616. }
  617. void GDScriptWorkspace::completion(const LSP::CompletionParams &p_params, List<ScriptLanguage::CodeCompletionOption> *r_options) {
  618. String path = get_file_path(p_params.textDocument.uri);
  619. String call_hint;
  620. bool forced = false;
  621. if (const ExtendGDScriptParser *parser = get_parse_result(path)) {
  622. Node *owner_scene_node = _get_owner_scene_node(path);
  623. Array stack;
  624. Node *current = nullptr;
  625. if (owner_scene_node != nullptr) {
  626. stack.push_back(owner_scene_node);
  627. while (!stack.is_empty()) {
  628. current = Object::cast_to<Node>(stack.pop_back());
  629. Ref<GDScript> scr = current->get_script();
  630. if (scr.is_valid() && GDScript::is_canonically_equal_paths(scr->get_path(), path)) {
  631. break;
  632. }
  633. for (int i = 0; i < current->get_child_count(); ++i) {
  634. stack.push_back(current->get_child(i));
  635. }
  636. }
  637. Ref<GDScript> scr = current->get_script();
  638. if (scr.is_null() || !GDScript::is_canonically_equal_paths(scr->get_path(), path)) {
  639. current = owner_scene_node;
  640. }
  641. }
  642. String code = parser->get_text_for_completion(p_params.position);
  643. GDScriptLanguage::get_singleton()->complete_code(code, path, current, r_options, forced, call_hint);
  644. if (owner_scene_node) {
  645. memdelete(owner_scene_node);
  646. }
  647. }
  648. }
  649. const LSP::DocumentSymbol *GDScriptWorkspace::resolve_symbol(const LSP::TextDocumentPositionParams &p_doc_pos, const String &p_symbol_name, bool p_func_required) {
  650. const LSP::DocumentSymbol *symbol = nullptr;
  651. String path = get_file_path(p_doc_pos.textDocument.uri);
  652. if (const ExtendGDScriptParser *parser = get_parse_result(path)) {
  653. String symbol_identifier = p_symbol_name;
  654. if (symbol_identifier.get_slice_count("(") > 0) {
  655. symbol_identifier = symbol_identifier.get_slicec('(', 0);
  656. }
  657. LSP::Position pos = p_doc_pos.position;
  658. if (symbol_identifier.is_empty()) {
  659. LSP::Range range;
  660. symbol_identifier = parser->get_identifier_under_position(p_doc_pos.position, range);
  661. pos.character = range.end.character;
  662. }
  663. if (!symbol_identifier.is_empty()) {
  664. if (ScriptServer::is_global_class(symbol_identifier)) {
  665. String class_path = ScriptServer::get_global_class_path(symbol_identifier);
  666. symbol = get_script_symbol(class_path);
  667. } else {
  668. ScriptLanguage::LookupResult ret;
  669. if (symbol_identifier == "new" && parser->get_lines()[p_doc_pos.position.line].remove_chars(" \t").contains("new(")) {
  670. symbol_identifier = "_init";
  671. }
  672. if (OK == GDScriptLanguage::get_singleton()->lookup_code(parser->get_text_for_lookup_symbol(pos, symbol_identifier, p_func_required), symbol_identifier, path, nullptr, ret)) {
  673. if (ret.location >= 0) {
  674. String target_script_path = path;
  675. if (ret.script.is_valid()) {
  676. target_script_path = ret.script->get_path();
  677. } else if (!ret.script_path.is_empty()) {
  678. target_script_path = ret.script_path;
  679. }
  680. if (const ExtendGDScriptParser *target_parser = get_parse_result(target_script_path)) {
  681. symbol = target_parser->get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(ret.location), symbol_identifier);
  682. if (symbol) {
  683. switch (symbol->kind) {
  684. case LSP::SymbolKind::Function: {
  685. if (symbol->name != symbol_identifier) {
  686. symbol = get_parameter_symbol(symbol, symbol_identifier);
  687. }
  688. } break;
  689. }
  690. }
  691. }
  692. } else {
  693. String member = ret.class_member;
  694. if (member.is_empty() && symbol_identifier != ret.class_name) {
  695. member = symbol_identifier;
  696. }
  697. symbol = get_native_symbol(ret.class_name, member);
  698. }
  699. } else {
  700. symbol = get_local_symbol_at(parser, symbol_identifier, p_doc_pos.position);
  701. if (!symbol) {
  702. symbol = parser->get_member_symbol(symbol_identifier);
  703. }
  704. }
  705. }
  706. }
  707. }
  708. return symbol;
  709. }
  710. void GDScriptWorkspace::resolve_related_symbols(const LSP::TextDocumentPositionParams &p_doc_pos, List<const LSP::DocumentSymbol *> &r_list) {
  711. String path = get_file_path(p_doc_pos.textDocument.uri);
  712. if (const ExtendGDScriptParser *parser = get_parse_result(path)) {
  713. String symbol_identifier;
  714. LSP::Range range;
  715. symbol_identifier = parser->get_identifier_under_position(p_doc_pos.position, range);
  716. for (const KeyValue<StringName, ClassMembers> &E : native_members) {
  717. const ClassMembers &members = native_members.get(E.key);
  718. if (const LSP::DocumentSymbol *const *symbol = members.getptr(symbol_identifier)) {
  719. r_list.push_back(*symbol);
  720. }
  721. }
  722. for (const KeyValue<String, ExtendGDScriptParser *> &E : scripts) {
  723. const ExtendGDScriptParser *scr = E.value;
  724. const ClassMembers &members = scr->get_members();
  725. if (const LSP::DocumentSymbol *const *symbol = members.getptr(symbol_identifier)) {
  726. r_list.push_back(*symbol);
  727. }
  728. for (const KeyValue<String, ClassMembers> &F : scr->get_inner_classes()) {
  729. const ClassMembers *inner_class = &F.value;
  730. if (const LSP::DocumentSymbol *const *symbol = inner_class->getptr(symbol_identifier)) {
  731. r_list.push_back(*symbol);
  732. }
  733. }
  734. }
  735. }
  736. }
  737. const LSP::DocumentSymbol *GDScriptWorkspace::resolve_native_symbol(const LSP::NativeSymbolInspectParams &p_params) {
  738. if (HashMap<StringName, LSP::DocumentSymbol>::Iterator E = native_symbols.find(p_params.native_class)) {
  739. const LSP::DocumentSymbol &symbol = E->value;
  740. if (p_params.symbol_name.is_empty() || p_params.symbol_name == symbol.name) {
  741. return &symbol;
  742. }
  743. for (int i = 0; i < symbol.children.size(); ++i) {
  744. if (symbol.children[i].name == p_params.symbol_name) {
  745. return &(symbol.children[i]);
  746. }
  747. }
  748. }
  749. return nullptr;
  750. }
  751. void GDScriptWorkspace::resolve_document_links(const String &p_uri, List<LSP::DocumentLink> &r_list) {
  752. if (const ExtendGDScriptParser *parser = get_parse_successed_script(get_file_path(p_uri))) {
  753. const List<LSP::DocumentLink> &links = parser->get_document_links();
  754. for (const LSP::DocumentLink &E : links) {
  755. r_list.push_back(E);
  756. }
  757. }
  758. }
  759. Dictionary GDScriptWorkspace::generate_script_api(const String &p_path) {
  760. Dictionary api;
  761. if (const ExtendGDScriptParser *parser = get_parse_successed_script(p_path)) {
  762. api = parser->generate_api();
  763. }
  764. return api;
  765. }
  766. Error GDScriptWorkspace::resolve_signature(const LSP::TextDocumentPositionParams &p_doc_pos, LSP::SignatureHelp &r_signature) {
  767. if (const ExtendGDScriptParser *parser = get_parse_result(get_file_path(p_doc_pos.textDocument.uri))) {
  768. LSP::TextDocumentPositionParams text_pos;
  769. text_pos.textDocument = p_doc_pos.textDocument;
  770. if (parser->get_left_function_call(p_doc_pos.position, text_pos.position, r_signature.activeParameter) == OK) {
  771. List<const LSP::DocumentSymbol *> symbols;
  772. if (const LSP::DocumentSymbol *symbol = resolve_symbol(text_pos)) {
  773. symbols.push_back(symbol);
  774. } else if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) {
  775. GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_related_symbols(text_pos, symbols);
  776. }
  777. for (const LSP::DocumentSymbol *const &symbol : symbols) {
  778. if (symbol->kind == LSP::SymbolKind::Method || symbol->kind == LSP::SymbolKind::Function) {
  779. LSP::SignatureInformation signature_info;
  780. signature_info.label = symbol->detail;
  781. signature_info.documentation = symbol->render();
  782. for (int i = 0; i < symbol->children.size(); i++) {
  783. const LSP::DocumentSymbol &arg = symbol->children[i];
  784. LSP::ParameterInformation arg_info;
  785. arg_info.label = arg.name;
  786. signature_info.parameters.push_back(arg_info);
  787. }
  788. r_signature.signatures.push_back(signature_info);
  789. break;
  790. }
  791. }
  792. if (r_signature.signatures.size()) {
  793. return OK;
  794. }
  795. }
  796. }
  797. return ERR_METHOD_NOT_FOUND;
  798. }
  799. GDScriptWorkspace::GDScriptWorkspace() {}
  800. GDScriptWorkspace::~GDScriptWorkspace() {
  801. HashSet<String> cached_parsers;
  802. for (const KeyValue<String, ExtendGDScriptParser *> &E : parse_results) {
  803. cached_parsers.insert(E.key);
  804. }
  805. for (const KeyValue<String, ExtendGDScriptParser *> &E : scripts) {
  806. cached_parsers.insert(E.key);
  807. }
  808. for (const String &E : cached_parsers) {
  809. remove_cache_parser(E);
  810. }
  811. }