Debian Codegraph @

modules/gdscript/language_server/gdscript_workspace.cpp

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