gdscript_extend_parser.cpp 36 KB

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