gdscript_extend_parser.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  1. /**************************************************************************/
  2. /* gdscript_extend_parser.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_extend_parser.h"
  31. #include "../gdscript.h"
  32. #include "../gdscript_analyzer.h"
  33. #include "editor/editor_settings.h"
  34. #include "gdscript_language_protocol.h"
  35. #include "gdscript_workspace.h"
  36. int get_indent_size() {
  37. if (EditorSettings::get_singleton()) {
  38. return EditorSettings::get_singleton()->get_setting("text_editor/behavior/indent/size");
  39. } else {
  40. return 4;
  41. }
  42. }
  43. LSP::Position GodotPosition::to_lsp(const Vector<String> &p_lines) const {
  44. LSP::Position res;
  45. // Special case: `line = 0` -> root class (range covers everything).
  46. if (line <= 0) {
  47. return res;
  48. }
  49. // Special case: `line = p_lines.size() + 1` -> root class (range covers everything).
  50. if (line >= p_lines.size() + 1) {
  51. res.line = p_lines.size();
  52. return res;
  53. }
  54. res.line = line - 1;
  55. // Special case: `column = 0` -> Starts at beginning of line.
  56. if (column <= 0) {
  57. return res;
  58. }
  59. // Note: character outside of `pos_line.length()-1` is valid.
  60. res.character = column - 1;
  61. String pos_line = p_lines[res.line];
  62. if (pos_line.contains_char('\t')) {
  63. int tab_size = get_indent_size();
  64. int in_col = 1;
  65. int res_char = 0;
  66. while (res_char < pos_line.size() && in_col < column) {
  67. if (pos_line[res_char] == '\t') {
  68. in_col += tab_size;
  69. res_char++;
  70. } else {
  71. in_col++;
  72. res_char++;
  73. }
  74. }
  75. res.character = res_char;
  76. }
  77. return res;
  78. }
  79. GodotPosition GodotPosition::from_lsp(const LSP::Position p_pos, const Vector<String> &p_lines) {
  80. GodotPosition res(p_pos.line + 1, p_pos.character + 1);
  81. // Line outside of actual text is valid (-> pos/cursor at end of text).
  82. if (res.line > p_lines.size()) {
  83. return res;
  84. }
  85. String line = p_lines[p_pos.line];
  86. int tabs_before_char = 0;
  87. for (int i = 0; i < p_pos.character && i < line.length(); i++) {
  88. if (line[i] == '\t') {
  89. tabs_before_char++;
  90. }
  91. }
  92. if (tabs_before_char > 0) {
  93. int tab_size = get_indent_size();
  94. res.column += tabs_before_char * (tab_size - 1);
  95. }
  96. return res;
  97. }
  98. LSP::Range GodotRange::to_lsp(const Vector<String> &p_lines) const {
  99. LSP::Range res;
  100. res.start = start.to_lsp(p_lines);
  101. res.end = end.to_lsp(p_lines);
  102. return res;
  103. }
  104. GodotRange GodotRange::from_lsp(const LSP::Range &p_range, const Vector<String> &p_lines) {
  105. GodotPosition start = GodotPosition::from_lsp(p_range.start, p_lines);
  106. GodotPosition end = GodotPosition::from_lsp(p_range.end, p_lines);
  107. return GodotRange(start, end);
  108. }
  109. void ExtendGDScriptParser::update_diagnostics() {
  110. diagnostics.clear();
  111. const List<ParserError> &parser_errors = get_errors();
  112. for (const ParserError &error : parser_errors) {
  113. LSP::Diagnostic diagnostic;
  114. diagnostic.severity = LSP::DiagnosticSeverity::Error;
  115. diagnostic.message = error.message;
  116. diagnostic.source = "gdscript";
  117. diagnostic.code = -1;
  118. LSP::Range range;
  119. LSP::Position pos;
  120. const PackedStringArray line_array = get_lines();
  121. int line = CLAMP(LINE_NUMBER_TO_INDEX(error.line), 0, line_array.size() - 1);
  122. const String &line_text = line_array[line];
  123. pos.line = line;
  124. pos.character = line_text.length() - line_text.strip_edges(true, false).length();
  125. range.start = pos;
  126. range.end = range.start;
  127. range.end.character = line_text.strip_edges(false).length();
  128. diagnostic.range = range;
  129. diagnostics.push_back(diagnostic);
  130. }
  131. const List<GDScriptWarning> &parser_warnings = get_warnings();
  132. for (const GDScriptWarning &warning : parser_warnings) {
  133. LSP::Diagnostic diagnostic;
  134. diagnostic.severity = LSP::DiagnosticSeverity::Warning;
  135. diagnostic.message = "(" + warning.get_name() + "): " + warning.get_message();
  136. diagnostic.source = "gdscript";
  137. diagnostic.code = warning.code;
  138. LSP::Range range;
  139. LSP::Position pos;
  140. int line = LINE_NUMBER_TO_INDEX(warning.start_line);
  141. const String &line_text = get_lines()[line];
  142. pos.line = line;
  143. pos.character = line_text.length() - line_text.strip_edges(true, false).length();
  144. range.start = pos;
  145. range.end = pos;
  146. range.end.character = line_text.strip_edges(false).length();
  147. diagnostic.range = range;
  148. diagnostics.push_back(diagnostic);
  149. }
  150. }
  151. void ExtendGDScriptParser::update_symbols() {
  152. members.clear();
  153. if (const GDScriptParser::ClassNode *gdclass = dynamic_cast<const GDScriptParser::ClassNode *>(get_tree())) {
  154. parse_class_symbol(gdclass, class_symbol);
  155. for (int i = 0; i < class_symbol.children.size(); i++) {
  156. const LSP::DocumentSymbol &symbol = class_symbol.children[i];
  157. members.insert(symbol.name, &symbol);
  158. // Cache level one inner classes.
  159. if (symbol.kind == LSP::SymbolKind::Class) {
  160. ClassMembers inner_class;
  161. for (int j = 0; j < symbol.children.size(); j++) {
  162. const LSP::DocumentSymbol &s = symbol.children[j];
  163. inner_class.insert(s.name, &s);
  164. }
  165. inner_classes.insert(symbol.name, inner_class);
  166. }
  167. }
  168. }
  169. }
  170. void ExtendGDScriptParser::update_document_links(const String &p_code) {
  171. document_links.clear();
  172. GDScriptTokenizerText scr_tokenizer;
  173. Ref<FileAccess> fs = FileAccess::create(FileAccess::ACCESS_RESOURCES);
  174. scr_tokenizer.set_source_code(p_code);
  175. while (true) {
  176. GDScriptTokenizer::Token token = scr_tokenizer.scan();
  177. if (token.type == GDScriptTokenizer::Token::TK_EOF) {
  178. break;
  179. } else if (token.type == GDScriptTokenizer::Token::LITERAL) {
  180. const Variant &const_val = token.literal;
  181. if (const_val.get_type() == Variant::STRING) {
  182. String scr_path = const_val;
  183. if (scr_path.is_relative_path()) {
  184. scr_path = get_path().get_base_dir().path_join(scr_path).simplify_path();
  185. }
  186. bool exists = fs->file_exists(scr_path);
  187. if (exists) {
  188. String value = const_val;
  189. LSP::DocumentLink link;
  190. link.target = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_uri(scr_path);
  191. link.range = GodotRange(GodotPosition(token.start_line, token.start_column), GodotPosition(token.end_line, token.end_column)).to_lsp(lines);
  192. document_links.push_back(link);
  193. }
  194. }
  195. }
  196. }
  197. }
  198. LSP::Range ExtendGDScriptParser::range_of_node(const GDScriptParser::Node *p_node) const {
  199. GodotPosition start(p_node->start_line, p_node->start_column);
  200. GodotPosition end(p_node->end_line, p_node->end_column);
  201. return GodotRange(start, end).to_lsp(lines);
  202. }
  203. void ExtendGDScriptParser::parse_class_symbol(const GDScriptParser::ClassNode *p_class, LSP::DocumentSymbol &r_symbol) {
  204. const String uri = get_uri();
  205. r_symbol.uri = uri;
  206. r_symbol.script_path = path;
  207. r_symbol.children.clear();
  208. r_symbol.name = p_class->identifier != nullptr ? String(p_class->identifier->name) : String();
  209. if (r_symbol.name.is_empty()) {
  210. r_symbol.name = path.get_file();
  211. }
  212. r_symbol.kind = LSP::SymbolKind::Class;
  213. r_symbol.deprecated = false;
  214. r_symbol.range = range_of_node(p_class);
  215. if (p_class->identifier) {
  216. r_symbol.selectionRange = range_of_node(p_class->identifier);
  217. } else {
  218. // No meaningful `selectionRange`, but we must ensure that it is inside of `range`.
  219. r_symbol.selectionRange.start = r_symbol.range.start;
  220. r_symbol.selectionRange.end = r_symbol.range.start;
  221. }
  222. r_symbol.detail = "class " + r_symbol.name;
  223. {
  224. String doc = p_class->doc_data.description;
  225. if (!p_class->doc_data.description.is_empty()) {
  226. doc += "\n\n" + p_class->doc_data.description;
  227. }
  228. if (!p_class->doc_data.tutorials.is_empty()) {
  229. doc += "\n";
  230. for (const Pair<String, String> &tutorial : p_class->doc_data.tutorials) {
  231. if (tutorial.first.is_empty()) {
  232. doc += vformat("\n@tutorial: %s", tutorial.second);
  233. } else {
  234. doc += vformat("\n@tutorial(%s): %s", tutorial.first, tutorial.second);
  235. }
  236. }
  237. }
  238. r_symbol.documentation = doc;
  239. }
  240. for (int i = 0; i < p_class->members.size(); i++) {
  241. const ClassNode::Member &m = p_class->members[i];
  242. switch (m.type) {
  243. case ClassNode::Member::VARIABLE: {
  244. LSP::DocumentSymbol symbol;
  245. symbol.name = m.variable->identifier->name;
  246. symbol.kind = m.variable->property == VariableNode::PROP_NONE ? LSP::SymbolKind::Variable : LSP::SymbolKind::Property;
  247. symbol.deprecated = false;
  248. symbol.range = range_of_node(m.variable);
  249. symbol.selectionRange = range_of_node(m.variable->identifier);
  250. if (m.variable->exported) {
  251. symbol.detail += "@export ";
  252. }
  253. symbol.detail += "var " + m.variable->identifier->name;
  254. if (m.get_datatype().is_hard_type()) {
  255. symbol.detail += ": " + m.get_datatype().to_string();
  256. }
  257. if (m.variable->initializer != nullptr && m.variable->initializer->is_constant) {
  258. symbol.detail += " = " + m.variable->initializer->reduced_value.to_json_string();
  259. }
  260. symbol.documentation = m.variable->doc_data.description;
  261. symbol.uri = uri;
  262. symbol.script_path = path;
  263. if (m.variable->initializer && m.variable->initializer->type == GDScriptParser::Node::LAMBDA) {
  264. GDScriptParser::LambdaNode *lambda_node = (GDScriptParser::LambdaNode *)m.variable->initializer;
  265. LSP::DocumentSymbol lambda;
  266. parse_function_symbol(lambda_node->function, lambda);
  267. // Merge lambda into current variable.
  268. symbol.children.append_array(lambda.children);
  269. }
  270. if (m.variable->getter && m.variable->getter->type == GDScriptParser::Node::FUNCTION) {
  271. LSP::DocumentSymbol get_symbol;
  272. parse_function_symbol(m.variable->getter, get_symbol);
  273. get_symbol.local = true;
  274. symbol.children.push_back(get_symbol);
  275. }
  276. if (m.variable->setter && m.variable->setter->type == GDScriptParser::Node::FUNCTION) {
  277. LSP::DocumentSymbol set_symbol;
  278. parse_function_symbol(m.variable->setter, set_symbol);
  279. set_symbol.local = true;
  280. symbol.children.push_back(set_symbol);
  281. }
  282. r_symbol.children.push_back(symbol);
  283. } break;
  284. case ClassNode::Member::CONSTANT: {
  285. LSP::DocumentSymbol symbol;
  286. symbol.name = m.constant->identifier->name;
  287. symbol.kind = LSP::SymbolKind::Constant;
  288. symbol.deprecated = false;
  289. symbol.range = range_of_node(m.constant);
  290. symbol.selectionRange = range_of_node(m.constant->identifier);
  291. symbol.documentation = m.constant->doc_data.description;
  292. symbol.uri = uri;
  293. symbol.script_path = path;
  294. symbol.detail = "const " + symbol.name;
  295. if (m.constant->get_datatype().is_hard_type()) {
  296. symbol.detail += ": " + m.constant->get_datatype().to_string();
  297. }
  298. const Variant &default_value = m.constant->initializer->reduced_value;
  299. String value_text;
  300. if (default_value.get_type() == Variant::OBJECT) {
  301. Ref<Resource> res = default_value;
  302. if (res.is_valid() && !res->get_path().is_empty()) {
  303. value_text = "preload(\"" + res->get_path() + "\")";
  304. if (symbol.documentation.is_empty()) {
  305. if (HashMap<String, ExtendGDScriptParser *>::Iterator S = GDScriptLanguageProtocol::get_singleton()->get_workspace()->scripts.find(res->get_path())) {
  306. symbol.documentation = S->value->class_symbol.documentation;
  307. }
  308. }
  309. } else {
  310. value_text = default_value.to_json_string();
  311. }
  312. } else {
  313. value_text = default_value.to_json_string();
  314. }
  315. if (!value_text.is_empty()) {
  316. symbol.detail += " = " + value_text;
  317. }
  318. r_symbol.children.push_back(symbol);
  319. } break;
  320. case ClassNode::Member::SIGNAL: {
  321. LSP::DocumentSymbol symbol;
  322. symbol.name = m.signal->identifier->name;
  323. symbol.kind = LSP::SymbolKind::Event;
  324. symbol.deprecated = false;
  325. symbol.range = range_of_node(m.signal);
  326. symbol.selectionRange = range_of_node(m.signal->identifier);
  327. symbol.documentation = m.signal->doc_data.description;
  328. symbol.uri = uri;
  329. symbol.script_path = path;
  330. symbol.detail = "signal " + String(m.signal->identifier->name) + "(";
  331. for (int j = 0; j < m.signal->parameters.size(); j++) {
  332. if (j > 0) {
  333. symbol.detail += ", ";
  334. }
  335. symbol.detail += m.signal->parameters[j]->identifier->name;
  336. }
  337. symbol.detail += ")";
  338. for (GDScriptParser::ParameterNode *param : m.signal->parameters) {
  339. LSP::DocumentSymbol param_symbol;
  340. param_symbol.name = param->identifier->name;
  341. param_symbol.kind = LSP::SymbolKind::Variable;
  342. param_symbol.deprecated = false;
  343. param_symbol.local = true;
  344. param_symbol.range = range_of_node(param);
  345. param_symbol.selectionRange = range_of_node(param->identifier);
  346. param_symbol.uri = uri;
  347. param_symbol.script_path = path;
  348. param_symbol.detail = "var " + param_symbol.name;
  349. if (param->get_datatype().is_hard_type()) {
  350. param_symbol.detail += ": " + param->get_datatype().to_string();
  351. }
  352. symbol.children.push_back(param_symbol);
  353. }
  354. r_symbol.children.push_back(symbol);
  355. } break;
  356. case ClassNode::Member::ENUM_VALUE: {
  357. LSP::DocumentSymbol symbol;
  358. symbol.name = m.enum_value.identifier->name;
  359. symbol.kind = LSP::SymbolKind::EnumMember;
  360. symbol.deprecated = false;
  361. symbol.range.start = GodotPosition(m.enum_value.line, m.enum_value.start_column).to_lsp(lines);
  362. symbol.range.end = GodotPosition(m.enum_value.line, m.enum_value.end_column).to_lsp(lines);
  363. symbol.selectionRange = range_of_node(m.enum_value.identifier);
  364. symbol.documentation = m.enum_value.doc_data.description;
  365. symbol.uri = uri;
  366. symbol.script_path = path;
  367. symbol.detail = symbol.name + " = " + itos(m.enum_value.value);
  368. r_symbol.children.push_back(symbol);
  369. } break;
  370. case ClassNode::Member::ENUM: {
  371. LSP::DocumentSymbol symbol;
  372. symbol.name = m.m_enum->identifier->name;
  373. symbol.kind = LSP::SymbolKind::Enum;
  374. symbol.range = range_of_node(m.m_enum);
  375. symbol.selectionRange = range_of_node(m.m_enum->identifier);
  376. symbol.documentation = m.m_enum->doc_data.description;
  377. symbol.uri = uri;
  378. symbol.script_path = path;
  379. symbol.detail = "enum " + String(m.m_enum->identifier->name) + "{";
  380. for (int j = 0; j < m.m_enum->values.size(); j++) {
  381. if (j > 0) {
  382. symbol.detail += ", ";
  383. }
  384. symbol.detail += String(m.m_enum->values[j].identifier->name) + " = " + itos(m.m_enum->values[j].value);
  385. }
  386. symbol.detail += "}";
  387. for (GDScriptParser::EnumNode::Value value : m.m_enum->values) {
  388. LSP::DocumentSymbol child;
  389. child.name = value.identifier->name;
  390. child.kind = LSP::SymbolKind::EnumMember;
  391. child.deprecated = false;
  392. child.range.start = GodotPosition(value.line, value.start_column).to_lsp(lines);
  393. child.range.end = GodotPosition(value.line, value.end_column).to_lsp(lines);
  394. child.selectionRange = range_of_node(value.identifier);
  395. child.documentation = value.doc_data.description;
  396. child.uri = uri;
  397. child.script_path = path;
  398. child.detail = child.name + " = " + itos(value.value);
  399. symbol.children.push_back(child);
  400. }
  401. r_symbol.children.push_back(symbol);
  402. } break;
  403. case ClassNode::Member::FUNCTION: {
  404. LSP::DocumentSymbol symbol;
  405. parse_function_symbol(m.function, symbol);
  406. r_symbol.children.push_back(symbol);
  407. } break;
  408. case ClassNode::Member::CLASS: {
  409. LSP::DocumentSymbol symbol;
  410. parse_class_symbol(m.m_class, symbol);
  411. r_symbol.children.push_back(symbol);
  412. } break;
  413. case ClassNode::Member::GROUP:
  414. break; // No-op, but silences warnings.
  415. case ClassNode::Member::UNDEFINED:
  416. break; // Unreachable.
  417. }
  418. }
  419. }
  420. void ExtendGDScriptParser::parse_function_symbol(const GDScriptParser::FunctionNode *p_func, LSP::DocumentSymbol &r_symbol) {
  421. const String uri = get_uri();
  422. bool is_named = p_func->identifier != nullptr;
  423. r_symbol.name = is_named ? p_func->identifier->name : "";
  424. r_symbol.kind = (p_func->is_static || p_func->source_lambda != nullptr) ? LSP::SymbolKind::Function : LSP::SymbolKind::Method;
  425. r_symbol.detail = "func";
  426. if (is_named) {
  427. r_symbol.detail += " " + String(p_func->identifier->name);
  428. }
  429. r_symbol.detail += "(";
  430. r_symbol.deprecated = false;
  431. r_symbol.range = range_of_node(p_func);
  432. if (is_named) {
  433. r_symbol.selectionRange = range_of_node(p_func->identifier);
  434. } else {
  435. r_symbol.selectionRange.start = r_symbol.selectionRange.end = r_symbol.range.start;
  436. }
  437. r_symbol.documentation = p_func->doc_data.description;
  438. r_symbol.uri = uri;
  439. r_symbol.script_path = path;
  440. String parameters;
  441. for (int i = 0; i < p_func->parameters.size(); i++) {
  442. const ParameterNode *parameter = p_func->parameters[i];
  443. if (i > 0) {
  444. parameters += ", ";
  445. }
  446. parameters += String(parameter->identifier->name);
  447. if (parameter->get_datatype().is_hard_type()) {
  448. parameters += ": " + parameter->get_datatype().to_string();
  449. }
  450. if (parameter->initializer != nullptr) {
  451. parameters += " = " + parameter->initializer->reduced_value.to_json_string();
  452. }
  453. }
  454. r_symbol.detail += parameters + ")";
  455. if (p_func->get_datatype().is_hard_type()) {
  456. r_symbol.detail += " -> " + p_func->get_datatype().to_string();
  457. }
  458. List<GDScriptParser::SuiteNode *> function_nodes;
  459. List<GDScriptParser::Node *> node_stack;
  460. node_stack.push_back(p_func->body);
  461. while (!node_stack.is_empty()) {
  462. GDScriptParser::Node *node = node_stack.front()->get();
  463. node_stack.pop_front();
  464. switch (node->type) {
  465. case GDScriptParser::TypeNode::IF: {
  466. GDScriptParser::IfNode *if_node = (GDScriptParser::IfNode *)node;
  467. node_stack.push_back(if_node->true_block);
  468. if (if_node->false_block) {
  469. node_stack.push_back(if_node->false_block);
  470. }
  471. } break;
  472. case GDScriptParser::TypeNode::FOR: {
  473. GDScriptParser::ForNode *for_node = (GDScriptParser::ForNode *)node;
  474. node_stack.push_back(for_node->loop);
  475. } break;
  476. case GDScriptParser::TypeNode::WHILE: {
  477. GDScriptParser::WhileNode *while_node = (GDScriptParser::WhileNode *)node;
  478. node_stack.push_back(while_node->loop);
  479. } break;
  480. case GDScriptParser::TypeNode::MATCH: {
  481. GDScriptParser::MatchNode *match_node = (GDScriptParser::MatchNode *)node;
  482. for (GDScriptParser::MatchBranchNode *branch_node : match_node->branches) {
  483. node_stack.push_back(branch_node);
  484. }
  485. } break;
  486. case GDScriptParser::TypeNode::MATCH_BRANCH: {
  487. GDScriptParser::MatchBranchNode *match_node = (GDScriptParser::MatchBranchNode *)node;
  488. node_stack.push_back(match_node->block);
  489. } break;
  490. case GDScriptParser::TypeNode::SUITE: {
  491. GDScriptParser::SuiteNode *suite_node = (GDScriptParser::SuiteNode *)node;
  492. function_nodes.push_back(suite_node);
  493. for (int i = 0; i < suite_node->statements.size(); ++i) {
  494. node_stack.push_back(suite_node->statements[i]);
  495. }
  496. } break;
  497. default:
  498. continue;
  499. }
  500. }
  501. for (List<GDScriptParser::SuiteNode *>::Element *N = function_nodes.front(); N; N = N->next()) {
  502. const GDScriptParser::SuiteNode *suite_node = N->get();
  503. for (int i = 0; i < suite_node->locals.size(); i++) {
  504. const SuiteNode::Local &local = suite_node->locals[i];
  505. LSP::DocumentSymbol symbol;
  506. symbol.name = local.name;
  507. symbol.kind = local.type == SuiteNode::Local::CONSTANT ? LSP::SymbolKind::Constant : LSP::SymbolKind::Variable;
  508. switch (local.type) {
  509. case SuiteNode::Local::CONSTANT:
  510. symbol.range = range_of_node(local.constant);
  511. symbol.selectionRange = range_of_node(local.constant->identifier);
  512. break;
  513. case SuiteNode::Local::VARIABLE:
  514. symbol.range = range_of_node(local.variable);
  515. symbol.selectionRange = range_of_node(local.variable->identifier);
  516. if (local.variable->initializer && local.variable->initializer->type == GDScriptParser::Node::LAMBDA) {
  517. GDScriptParser::LambdaNode *lambda_node = (GDScriptParser::LambdaNode *)local.variable->initializer;
  518. LSP::DocumentSymbol lambda;
  519. parse_function_symbol(lambda_node->function, lambda);
  520. // Merge lambda into current variable.
  521. // -> Only interested in new variables, not lambda itself.
  522. symbol.children.append_array(lambda.children);
  523. }
  524. break;
  525. case SuiteNode::Local::PARAMETER:
  526. symbol.range = range_of_node(local.parameter);
  527. symbol.selectionRange = range_of_node(local.parameter->identifier);
  528. break;
  529. case SuiteNode::Local::FOR_VARIABLE:
  530. case SuiteNode::Local::PATTERN_BIND:
  531. symbol.range = range_of_node(local.bind);
  532. symbol.selectionRange = range_of_node(local.bind);
  533. break;
  534. default:
  535. // Fallback.
  536. symbol.range.start = GodotPosition(local.start_line, local.start_column).to_lsp(get_lines());
  537. symbol.range.end = GodotPosition(local.end_line, local.end_column).to_lsp(get_lines());
  538. symbol.selectionRange = symbol.range;
  539. break;
  540. }
  541. symbol.local = true;
  542. symbol.uri = uri;
  543. symbol.script_path = path;
  544. symbol.detail = local.type == SuiteNode::Local::CONSTANT ? "const " : "var ";
  545. symbol.detail += symbol.name;
  546. if (local.get_datatype().is_hard_type()) {
  547. symbol.detail += ": " + local.get_datatype().to_string();
  548. }
  549. switch (local.type) {
  550. case SuiteNode::Local::CONSTANT:
  551. symbol.documentation = local.constant->doc_data.description;
  552. break;
  553. case SuiteNode::Local::VARIABLE:
  554. symbol.documentation = local.variable->doc_data.description;
  555. break;
  556. default:
  557. break;
  558. }
  559. r_symbol.children.push_back(symbol);
  560. }
  561. }
  562. }
  563. String ExtendGDScriptParser::get_text_for_completion(const LSP::Position &p_cursor) const {
  564. String longthing;
  565. int len = lines.size();
  566. for (int i = 0; i < len; i++) {
  567. if (i == p_cursor.line) {
  568. longthing += lines[i].substr(0, p_cursor.character);
  569. longthing += String::chr(0xFFFF); // Not unicode, represents the cursor.
  570. longthing += lines[i].substr(p_cursor.character);
  571. } else {
  572. longthing += lines[i];
  573. }
  574. if (i != len - 1) {
  575. longthing += "\n";
  576. }
  577. }
  578. return longthing;
  579. }
  580. String ExtendGDScriptParser::get_text_for_lookup_symbol(const LSP::Position &p_cursor, const String &p_symbol, bool p_func_required) const {
  581. String longthing;
  582. int len = lines.size();
  583. for (int i = 0; i < len; i++) {
  584. if (i == p_cursor.line) {
  585. String line = lines[i];
  586. String first_part = line.substr(0, p_cursor.character);
  587. String last_part = line.substr(p_cursor.character, lines[i].length());
  588. if (!p_symbol.is_empty()) {
  589. String left_cursor_text;
  590. for (int c = p_cursor.character - 1; c >= 0; c--) {
  591. left_cursor_text = line.substr(c, p_cursor.character - c);
  592. if (p_symbol.begins_with(left_cursor_text)) {
  593. first_part = line.substr(0, c);
  594. first_part += p_symbol;
  595. break;
  596. }
  597. }
  598. }
  599. longthing += first_part;
  600. longthing += String::chr(0xFFFF); // Not unicode, represents the cursor.
  601. if (p_func_required) {
  602. longthing += "("; // Tell the parser this is a function call.
  603. }
  604. longthing += last_part;
  605. } else {
  606. longthing += lines[i];
  607. }
  608. if (i != len - 1) {
  609. longthing += "\n";
  610. }
  611. }
  612. return longthing;
  613. }
  614. String ExtendGDScriptParser::get_identifier_under_position(const LSP::Position &p_position, LSP::Range &r_range) const {
  615. ERR_FAIL_INDEX_V(p_position.line, lines.size(), "");
  616. String line = lines[p_position.line];
  617. if (line.is_empty()) {
  618. return "";
  619. }
  620. ERR_FAIL_INDEX_V(p_position.character, line.size(), "");
  621. // `p_position` cursor is BETWEEN chars, not ON chars.
  622. // ->
  623. // ```gdscript
  624. // var member| := some_func|(some_variable|)
  625. // ^ ^ ^
  626. // | | | cursor on `some_variable, position on `)`
  627. // | |
  628. // | | cursor on `some_func`, pos on `(`
  629. // |
  630. // | cursor on `member`, pos on ` ` (space)
  631. // ```
  632. // -> Move position to previous character if:
  633. // * Position not on valid identifier char.
  634. // * Prev position is valid identifier char.
  635. LSP::Position pos = p_position;
  636. if (
  637. pos.character >= line.length() // Cursor at end of line.
  638. || (!is_ascii_identifier_char(line[pos.character]) // Not on valid identifier char.
  639. && (pos.character > 0 // Not line start -> there is a prev char.
  640. && is_ascii_identifier_char(line[pos.character - 1]) // Prev is valid identifier char.
  641. ))) {
  642. pos.character--;
  643. }
  644. int start_pos = pos.character;
  645. for (int c = pos.character; c >= 0; c--) {
  646. start_pos = c;
  647. char32_t ch = line[c];
  648. bool valid_char = is_ascii_identifier_char(ch);
  649. if (!valid_char) {
  650. break;
  651. }
  652. }
  653. int end_pos = pos.character;
  654. for (int c = pos.character; c < line.length(); c++) {
  655. char32_t ch = line[c];
  656. bool valid_char = is_ascii_identifier_char(ch);
  657. if (!valid_char) {
  658. break;
  659. }
  660. end_pos = c;
  661. }
  662. if (start_pos < end_pos) {
  663. r_range.start.line = r_range.end.line = pos.line;
  664. r_range.start.character = start_pos + 1;
  665. r_range.end.character = end_pos + 1;
  666. return line.substr(start_pos + 1, end_pos - start_pos);
  667. }
  668. return "";
  669. }
  670. String ExtendGDScriptParser::get_uri() const {
  671. return GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_uri(path);
  672. }
  673. const LSP::DocumentSymbol *ExtendGDScriptParser::search_symbol_defined_at_line(int p_line, const LSP::DocumentSymbol &p_parent, const String &p_symbol_name) const {
  674. const LSP::DocumentSymbol *ret = nullptr;
  675. if (p_line < p_parent.range.start.line) {
  676. return ret;
  677. } else if (p_parent.range.start.line == p_line && (p_symbol_name.is_empty() || p_parent.name == p_symbol_name)) {
  678. return &p_parent;
  679. } else {
  680. for (int i = 0; i < p_parent.children.size(); i++) {
  681. ret = search_symbol_defined_at_line(p_line, p_parent.children[i], p_symbol_name);
  682. if (ret) {
  683. break;
  684. }
  685. }
  686. }
  687. return ret;
  688. }
  689. Error ExtendGDScriptParser::get_left_function_call(const LSP::Position &p_position, LSP::Position &r_func_pos, int &r_arg_index) const {
  690. ERR_FAIL_INDEX_V(p_position.line, lines.size(), ERR_INVALID_PARAMETER);
  691. int bracket_stack = 0;
  692. int index = 0;
  693. bool found = false;
  694. for (int l = p_position.line; l >= 0; --l) {
  695. String line = lines[l];
  696. int c = line.length() - 1;
  697. if (l == p_position.line) {
  698. c = MIN(c, p_position.character - 1);
  699. }
  700. while (c >= 0) {
  701. const char32_t &character = line[c];
  702. if (character == ')') {
  703. ++bracket_stack;
  704. } else if (character == '(') {
  705. --bracket_stack;
  706. if (bracket_stack < 0) {
  707. found = true;
  708. }
  709. }
  710. if (bracket_stack <= 0 && character == ',') {
  711. ++index;
  712. }
  713. --c;
  714. if (found) {
  715. r_func_pos.character = c;
  716. break;
  717. }
  718. }
  719. if (found) {
  720. r_func_pos.line = l;
  721. r_arg_index = index;
  722. return OK;
  723. }
  724. }
  725. return ERR_METHOD_NOT_FOUND;
  726. }
  727. const LSP::DocumentSymbol *ExtendGDScriptParser::get_symbol_defined_at_line(int p_line, const String &p_symbol_name) const {
  728. if (p_line <= 0) {
  729. return &class_symbol;
  730. }
  731. return search_symbol_defined_at_line(p_line, class_symbol, p_symbol_name);
  732. }
  733. const LSP::DocumentSymbol *ExtendGDScriptParser::get_member_symbol(const String &p_name, const String &p_subclass) const {
  734. if (p_subclass.is_empty()) {
  735. const LSP::DocumentSymbol *const *ptr = members.getptr(p_name);
  736. if (ptr) {
  737. return *ptr;
  738. }
  739. } else {
  740. if (const ClassMembers *_class = inner_classes.getptr(p_subclass)) {
  741. const LSP::DocumentSymbol *const *ptr = _class->getptr(p_name);
  742. if (ptr) {
  743. return *ptr;
  744. }
  745. }
  746. }
  747. return nullptr;
  748. }
  749. const List<LSP::DocumentLink> &ExtendGDScriptParser::get_document_links() const {
  750. return document_links;
  751. }
  752. const Array &ExtendGDScriptParser::get_member_completions() {
  753. if (member_completions.is_empty()) {
  754. for (const KeyValue<String, const LSP::DocumentSymbol *> &E : members) {
  755. const LSP::DocumentSymbol *symbol = E.value;
  756. LSP::CompletionItem item = symbol->make_completion_item();
  757. item.data = JOIN_SYMBOLS(path, E.key);
  758. member_completions.push_back(item.to_json());
  759. }
  760. for (const KeyValue<String, ClassMembers> &E : inner_classes) {
  761. const ClassMembers *inner_class = &E.value;
  762. for (const KeyValue<String, const LSP::DocumentSymbol *> &F : *inner_class) {
  763. const LSP::DocumentSymbol *symbol = F.value;
  764. LSP::CompletionItem item = symbol->make_completion_item();
  765. item.data = JOIN_SYMBOLS(path, JOIN_SYMBOLS(E.key, F.key));
  766. member_completions.push_back(item.to_json());
  767. }
  768. }
  769. }
  770. return member_completions;
  771. }
  772. Dictionary ExtendGDScriptParser::dump_function_api(const GDScriptParser::FunctionNode *p_func) const {
  773. Dictionary func;
  774. ERR_FAIL_NULL_V(p_func, func);
  775. func["name"] = p_func->identifier->name;
  776. func["return_type"] = p_func->get_datatype().to_string();
  777. func["rpc_config"] = p_func->rpc_config;
  778. Array parameters;
  779. for (int i = 0; i < p_func->parameters.size(); i++) {
  780. Dictionary arg;
  781. arg["name"] = p_func->parameters[i]->identifier->name;
  782. arg["type"] = p_func->parameters[i]->get_datatype().to_string();
  783. if (p_func->parameters[i]->initializer != nullptr) {
  784. arg["default_value"] = p_func->parameters[i]->initializer->reduced_value;
  785. }
  786. parameters.push_back(arg);
  787. }
  788. if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(p_func->start_line))) {
  789. func["signature"] = symbol->detail;
  790. func["description"] = symbol->documentation;
  791. }
  792. func["arguments"] = parameters;
  793. return func;
  794. }
  795. Dictionary ExtendGDScriptParser::dump_class_api(const GDScriptParser::ClassNode *p_class) const {
  796. Dictionary class_api;
  797. ERR_FAIL_NULL_V(p_class, class_api);
  798. class_api["name"] = p_class->identifier != nullptr ? String(p_class->identifier->name) : String();
  799. class_api["path"] = path;
  800. Array extends_class;
  801. for (int i = 0; i < p_class->extends.size(); i++) {
  802. extends_class.append(String(p_class->extends[i]->name));
  803. }
  804. class_api["extends_class"] = extends_class;
  805. class_api["extends_file"] = String(p_class->extends_path);
  806. class_api["icon"] = String(p_class->icon_path);
  807. if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(p_class->start_line))) {
  808. class_api["signature"] = symbol->detail;
  809. class_api["description"] = symbol->documentation;
  810. }
  811. Array nested_classes;
  812. Array constants;
  813. Array class_members;
  814. Array signals;
  815. Array methods;
  816. Array static_functions;
  817. for (int i = 0; i < p_class->members.size(); i++) {
  818. const ClassNode::Member &m = p_class->members[i];
  819. switch (m.type) {
  820. case ClassNode::Member::CLASS:
  821. nested_classes.push_back(dump_class_api(m.m_class));
  822. break;
  823. case ClassNode::Member::CONSTANT: {
  824. Dictionary api;
  825. api["name"] = m.constant->identifier->name;
  826. api["value"] = m.constant->initializer->reduced_value;
  827. api["data_type"] = m.constant->get_datatype().to_string();
  828. if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.constant->start_line))) {
  829. api["signature"] = symbol->detail;
  830. api["description"] = symbol->documentation;
  831. }
  832. constants.push_back(api);
  833. } break;
  834. case ClassNode::Member::ENUM_VALUE: {
  835. Dictionary api;
  836. api["name"] = m.enum_value.identifier->name;
  837. api["value"] = m.enum_value.value;
  838. api["data_type"] = m.get_datatype().to_string();
  839. if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.enum_value.line))) {
  840. api["signature"] = symbol->detail;
  841. api["description"] = symbol->documentation;
  842. }
  843. constants.push_back(api);
  844. } break;
  845. case ClassNode::Member::ENUM: {
  846. Dictionary enum_dict;
  847. for (int j = 0; j < m.m_enum->values.size(); j++) {
  848. enum_dict[m.m_enum->values[j].identifier->name] = m.m_enum->values[j].value;
  849. }
  850. Dictionary api;
  851. api["name"] = m.m_enum->identifier->name;
  852. api["value"] = enum_dict;
  853. api["data_type"] = m.get_datatype().to_string();
  854. if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.m_enum->start_line))) {
  855. api["signature"] = symbol->detail;
  856. api["description"] = symbol->documentation;
  857. }
  858. constants.push_back(api);
  859. } break;
  860. case ClassNode::Member::VARIABLE: {
  861. Dictionary api;
  862. api["name"] = m.variable->identifier->name;
  863. api["data_type"] = m.variable->get_datatype().to_string();
  864. api["default_value"] = m.variable->initializer != nullptr ? m.variable->initializer->reduced_value : Variant();
  865. api["setter"] = m.variable->setter ? ("@" + String(m.variable->identifier->name) + "_setter") : (m.variable->setter_pointer != nullptr ? String(m.variable->setter_pointer->name) : String());
  866. api["getter"] = m.variable->getter ? ("@" + String(m.variable->identifier->name) + "_getter") : (m.variable->getter_pointer != nullptr ? String(m.variable->getter_pointer->name) : String());
  867. api["export"] = m.variable->exported;
  868. if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.variable->start_line))) {
  869. api["signature"] = symbol->detail;
  870. api["description"] = symbol->documentation;
  871. }
  872. class_members.push_back(api);
  873. } break;
  874. case ClassNode::Member::SIGNAL: {
  875. Dictionary api;
  876. api["name"] = m.signal->identifier->name;
  877. Array pars;
  878. for (int j = 0; j < m.signal->parameters.size(); j++) {
  879. pars.append(String(m.signal->parameters[j]->identifier->name));
  880. }
  881. api["arguments"] = pars;
  882. if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.signal->start_line))) {
  883. api["signature"] = symbol->detail;
  884. api["description"] = symbol->documentation;
  885. }
  886. signals.push_back(api);
  887. } break;
  888. case ClassNode::Member::FUNCTION: {
  889. if (m.function->is_static) {
  890. static_functions.append(dump_function_api(m.function));
  891. } else {
  892. methods.append(dump_function_api(m.function));
  893. }
  894. } break;
  895. case ClassNode::Member::GROUP:
  896. break; // No-op, but silences warnings.
  897. case ClassNode::Member::UNDEFINED:
  898. break; // Unreachable.
  899. }
  900. }
  901. class_api["sub_classes"] = nested_classes;
  902. class_api["constants"] = constants;
  903. class_api["members"] = class_members;
  904. class_api["signals"] = signals;
  905. class_api["methods"] = methods;
  906. class_api["static_functions"] = static_functions;
  907. return class_api;
  908. }
  909. Dictionary ExtendGDScriptParser::generate_api() const {
  910. Dictionary api;
  911. if (const GDScriptParser::ClassNode *gdclass = dynamic_cast<const GDScriptParser::ClassNode *>(get_tree())) {
  912. api = dump_class_api(gdclass);
  913. }
  914. return api;
  915. }
  916. Error ExtendGDScriptParser::parse(const String &p_code, const String &p_path) {
  917. path = p_path;
  918. lines = p_code.split("\n");
  919. Error err = GDScriptParser::parse(p_code, p_path, false);
  920. GDScriptAnalyzer analyzer(this);
  921. if (err == OK) {
  922. err = analyzer.analyze();
  923. }
  924. update_diagnostics();
  925. update_symbols();
  926. update_document_links(p_code);
  927. return err;
  928. }