gdscript_extend_parser.cpp 35 KB

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