gdscript_extend_parser.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  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/settings/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.brief;
  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. ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(res->get_path());
  306. if (parser) {
  307. symbol.documentation = parser->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.start_column).to_lsp(lines);
  363. symbol.range.end = GodotPosition(m.enum_value.line, m.enum_value.end_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.start_column).to_lsp(lines);
  394. child.range.end = GodotPosition(value.line, value.end_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. if (p_func->is_vararg()) {
  456. if (!p_func->parameters.is_empty()) {
  457. parameters += ", ";
  458. }
  459. const ParameterNode *rest_param = p_func->rest_parameter;
  460. parameters += "..." + rest_param->identifier->name + ": " + rest_param->get_datatype().to_string();
  461. }
  462. r_symbol.detail += parameters + ")";
  463. const DataType return_type = p_func->get_datatype();
  464. if (return_type.is_hard_type()) {
  465. if (return_type.kind == DataType::BUILTIN && return_type.builtin_type == Variant::NIL) {
  466. r_symbol.detail += " -> void";
  467. } else {
  468. r_symbol.detail += " -> " + return_type.to_string();
  469. }
  470. }
  471. List<GDScriptParser::SuiteNode *> function_nodes;
  472. List<GDScriptParser::Node *> node_stack;
  473. node_stack.push_back(p_func->body);
  474. while (!node_stack.is_empty()) {
  475. GDScriptParser::Node *node = node_stack.front()->get();
  476. node_stack.pop_front();
  477. switch (node->type) {
  478. case GDScriptParser::TypeNode::IF: {
  479. GDScriptParser::IfNode *if_node = (GDScriptParser::IfNode *)node;
  480. node_stack.push_back(if_node->true_block);
  481. if (if_node->false_block) {
  482. node_stack.push_back(if_node->false_block);
  483. }
  484. } break;
  485. case GDScriptParser::TypeNode::FOR: {
  486. GDScriptParser::ForNode *for_node = (GDScriptParser::ForNode *)node;
  487. node_stack.push_back(for_node->loop);
  488. } break;
  489. case GDScriptParser::TypeNode::WHILE: {
  490. GDScriptParser::WhileNode *while_node = (GDScriptParser::WhileNode *)node;
  491. node_stack.push_back(while_node->loop);
  492. } break;
  493. case GDScriptParser::TypeNode::MATCH: {
  494. GDScriptParser::MatchNode *match_node = (GDScriptParser::MatchNode *)node;
  495. for (GDScriptParser::MatchBranchNode *branch_node : match_node->branches) {
  496. node_stack.push_back(branch_node);
  497. }
  498. } break;
  499. case GDScriptParser::TypeNode::MATCH_BRANCH: {
  500. GDScriptParser::MatchBranchNode *match_node = (GDScriptParser::MatchBranchNode *)node;
  501. node_stack.push_back(match_node->block);
  502. } break;
  503. case GDScriptParser::TypeNode::SUITE: {
  504. GDScriptParser::SuiteNode *suite_node = (GDScriptParser::SuiteNode *)node;
  505. function_nodes.push_back(suite_node);
  506. for (int i = 0; i < suite_node->statements.size(); ++i) {
  507. node_stack.push_back(suite_node->statements[i]);
  508. }
  509. } break;
  510. default:
  511. continue;
  512. }
  513. }
  514. for (List<GDScriptParser::SuiteNode *>::Element *N = function_nodes.front(); N; N = N->next()) {
  515. const GDScriptParser::SuiteNode *suite_node = N->get();
  516. for (int i = 0; i < suite_node->locals.size(); i++) {
  517. const SuiteNode::Local &local = suite_node->locals[i];
  518. LSP::DocumentSymbol symbol;
  519. symbol.name = local.name;
  520. symbol.kind = local.type == SuiteNode::Local::CONSTANT ? LSP::SymbolKind::Constant : LSP::SymbolKind::Variable;
  521. switch (local.type) {
  522. case SuiteNode::Local::CONSTANT:
  523. symbol.range = range_of_node(local.constant);
  524. symbol.selectionRange = range_of_node(local.constant->identifier);
  525. break;
  526. case SuiteNode::Local::VARIABLE:
  527. symbol.range = range_of_node(local.variable);
  528. symbol.selectionRange = range_of_node(local.variable->identifier);
  529. if (local.variable->initializer && local.variable->initializer->type == GDScriptParser::Node::LAMBDA) {
  530. GDScriptParser::LambdaNode *lambda_node = (GDScriptParser::LambdaNode *)local.variable->initializer;
  531. LSP::DocumentSymbol lambda;
  532. parse_function_symbol(lambda_node->function, lambda);
  533. // Merge lambda into current variable.
  534. // -> Only interested in new variables, not lambda itself.
  535. symbol.children.append_array(lambda.children);
  536. }
  537. break;
  538. case SuiteNode::Local::PARAMETER:
  539. symbol.range = range_of_node(local.parameter);
  540. symbol.selectionRange = range_of_node(local.parameter->identifier);
  541. break;
  542. case SuiteNode::Local::FOR_VARIABLE:
  543. case SuiteNode::Local::PATTERN_BIND:
  544. symbol.range = range_of_node(local.bind);
  545. symbol.selectionRange = range_of_node(local.bind);
  546. break;
  547. default:
  548. // Fallback.
  549. symbol.range.start = GodotPosition(local.start_line, local.start_column).to_lsp(get_lines());
  550. symbol.range.end = GodotPosition(local.end_line, local.end_column).to_lsp(get_lines());
  551. symbol.selectionRange = symbol.range;
  552. break;
  553. }
  554. symbol.local = true;
  555. symbol.uri = uri;
  556. symbol.script_path = path;
  557. symbol.detail = local.type == SuiteNode::Local::CONSTANT ? "const " : "var ";
  558. symbol.detail += symbol.name;
  559. if (local.get_datatype().is_hard_type()) {
  560. symbol.detail += ": " + local.get_datatype().to_string();
  561. }
  562. switch (local.type) {
  563. case SuiteNode::Local::CONSTANT:
  564. symbol.documentation = local.constant->doc_data.description;
  565. break;
  566. case SuiteNode::Local::VARIABLE:
  567. symbol.documentation = local.variable->doc_data.description;
  568. break;
  569. default:
  570. break;
  571. }
  572. r_symbol.children.push_back(symbol);
  573. }
  574. }
  575. }
  576. String ExtendGDScriptParser::get_text_for_completion(const LSP::Position &p_cursor) const {
  577. String longthing;
  578. int len = lines.size();
  579. for (int i = 0; i < len; i++) {
  580. if (i == p_cursor.line) {
  581. longthing += lines[i].substr(0, p_cursor.character);
  582. longthing += String::chr(0xFFFF); // Not unicode, represents the cursor.
  583. longthing += lines[i].substr(p_cursor.character);
  584. } else {
  585. longthing += lines[i];
  586. }
  587. if (i != len - 1) {
  588. longthing += "\n";
  589. }
  590. }
  591. return longthing;
  592. }
  593. String ExtendGDScriptParser::get_text_for_lookup_symbol(const LSP::Position &p_cursor, const String &p_symbol, bool p_func_required) const {
  594. String longthing;
  595. int len = lines.size();
  596. for (int i = 0; i < len; i++) {
  597. if (i == p_cursor.line) {
  598. // This code tries to insert the symbol into the preexisting code. Due to using a simple
  599. // algorithm, the results might not always match the option semantically (e.g. different
  600. // identifier name). This is fine because symbol lookup will prioritize the provided
  601. // symbol name over the actual code. Establishing a syntactic target (e.g. identifier)
  602. // is usually sufficient.
  603. String line = lines[i];
  604. String first_part = line.substr(0, p_cursor.character);
  605. String last_part = line.substr(p_cursor.character, lines[i].length());
  606. if (!p_symbol.is_empty()) {
  607. String left_cursor_text;
  608. for (int c = p_cursor.character - 1; c >= 0; c--) {
  609. left_cursor_text = line.substr(c, p_cursor.character - c);
  610. if (p_symbol.begins_with(left_cursor_text)) {
  611. first_part = line.substr(0, c);
  612. first_part += p_symbol;
  613. break;
  614. } else if (c == 0) {
  615. // No preexisting code that matches the option. Insert option in place.
  616. first_part += p_symbol;
  617. }
  618. }
  619. }
  620. longthing += first_part;
  621. longthing += String::chr(0xFFFF); // Not unicode, represents the cursor.
  622. if (p_func_required) {
  623. longthing += "("; // Tell the parser this is a function call.
  624. }
  625. longthing += last_part;
  626. } else {
  627. longthing += lines[i];
  628. }
  629. if (i != len - 1) {
  630. longthing += "\n";
  631. }
  632. }
  633. return longthing;
  634. }
  635. String ExtendGDScriptParser::get_identifier_under_position(const LSP::Position &p_position, LSP::Range &r_range) const {
  636. ERR_FAIL_INDEX_V(p_position.line, lines.size(), "");
  637. String line = lines[p_position.line];
  638. if (line.is_empty()) {
  639. return "";
  640. }
  641. ERR_FAIL_INDEX_V(p_position.character, line.size(), "");
  642. // `p_position` cursor is BETWEEN chars, not ON chars.
  643. // ->
  644. // ```gdscript
  645. // var member| := some_func|(some_variable|)
  646. // ^ ^ ^
  647. // | | | cursor on `some_variable, position on `)`
  648. // | |
  649. // | | cursor on `some_func`, pos on `(`
  650. // |
  651. // | cursor on `member`, pos on ` ` (space)
  652. // ```
  653. // -> Move position to previous character if:
  654. // * Position not on valid identifier char.
  655. // * Prev position is valid identifier char.
  656. LSP::Position pos = p_position;
  657. if (
  658. pos.character >= line.length() // Cursor at end of line.
  659. || (!is_unicode_identifier_continue(line[pos.character]) // Not on valid identifier char.
  660. && (pos.character > 0 // Not line start -> there is a prev char.
  661. && is_unicode_identifier_continue(line[pos.character - 1]) // Prev is valid identifier char.
  662. ))) {
  663. pos.character--;
  664. }
  665. int start_pos = pos.character;
  666. for (int c = pos.character; c >= 0; c--) {
  667. start_pos = c;
  668. char32_t ch = line[c];
  669. bool valid_char = is_unicode_identifier_continue(ch);
  670. if (!valid_char) {
  671. break;
  672. }
  673. }
  674. int end_pos = pos.character;
  675. for (int c = pos.character; c < line.length(); c++) {
  676. char32_t ch = line[c];
  677. bool valid_char = is_unicode_identifier_continue(ch);
  678. if (!valid_char) {
  679. break;
  680. }
  681. end_pos = c;
  682. }
  683. if (!is_unicode_identifier_start(line[start_pos + 1])) {
  684. return "";
  685. }
  686. if (start_pos < end_pos) {
  687. r_range.start.line = r_range.end.line = pos.line;
  688. r_range.start.character = start_pos + 1;
  689. r_range.end.character = end_pos + 1;
  690. return line.substr(start_pos + 1, end_pos - start_pos);
  691. }
  692. return "";
  693. }
  694. String ExtendGDScriptParser::get_uri() const {
  695. return GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_uri(path);
  696. }
  697. const LSP::DocumentSymbol *ExtendGDScriptParser::search_symbol_defined_at_line(int p_line, const LSP::DocumentSymbol &p_parent, const String &p_symbol_name) const {
  698. const LSP::DocumentSymbol *ret = nullptr;
  699. if (p_line < p_parent.range.start.line) {
  700. return ret;
  701. } else if (p_parent.range.start.line == p_line && (p_symbol_name.is_empty() || p_parent.name == p_symbol_name)) {
  702. return &p_parent;
  703. } else {
  704. for (int i = 0; i < p_parent.children.size(); i++) {
  705. ret = search_symbol_defined_at_line(p_line, p_parent.children[i], p_symbol_name);
  706. if (ret) {
  707. break;
  708. }
  709. }
  710. }
  711. return ret;
  712. }
  713. Error ExtendGDScriptParser::get_left_function_call(const LSP::Position &p_position, LSP::Position &r_func_pos, int &r_arg_index) const {
  714. ERR_FAIL_INDEX_V(p_position.line, lines.size(), ERR_INVALID_PARAMETER);
  715. int bracket_stack = 0;
  716. int index = 0;
  717. bool found = false;
  718. for (int l = p_position.line; l >= 0; --l) {
  719. String line = lines[l];
  720. int c = line.length() - 1;
  721. if (l == p_position.line) {
  722. c = MIN(c, p_position.character - 1);
  723. }
  724. while (c >= 0) {
  725. const char32_t &character = line[c];
  726. if (character == ')') {
  727. ++bracket_stack;
  728. } else if (character == '(') {
  729. --bracket_stack;
  730. if (bracket_stack < 0) {
  731. found = true;
  732. }
  733. }
  734. if (bracket_stack <= 0 && character == ',') {
  735. ++index;
  736. }
  737. --c;
  738. if (found) {
  739. r_func_pos.character = c;
  740. break;
  741. }
  742. }
  743. if (found) {
  744. r_func_pos.line = l;
  745. r_arg_index = index;
  746. return OK;
  747. }
  748. }
  749. return ERR_METHOD_NOT_FOUND;
  750. }
  751. const LSP::DocumentSymbol *ExtendGDScriptParser::get_symbol_defined_at_line(int p_line, const String &p_symbol_name) const {
  752. if (p_line <= 0) {
  753. return &class_symbol;
  754. }
  755. return search_symbol_defined_at_line(p_line, class_symbol, p_symbol_name);
  756. }
  757. const LSP::DocumentSymbol *ExtendGDScriptParser::get_member_symbol(const String &p_name, const String &p_subclass) const {
  758. if (p_subclass.is_empty()) {
  759. const LSP::DocumentSymbol *const *ptr = members.getptr(p_name);
  760. if (ptr) {
  761. return *ptr;
  762. }
  763. } else {
  764. if (const ClassMembers *_class = inner_classes.getptr(p_subclass)) {
  765. const LSP::DocumentSymbol *const *ptr = _class->getptr(p_name);
  766. if (ptr) {
  767. return *ptr;
  768. }
  769. }
  770. }
  771. return nullptr;
  772. }
  773. const List<LSP::DocumentLink> &ExtendGDScriptParser::get_document_links() const {
  774. return document_links;
  775. }
  776. const Array &ExtendGDScriptParser::get_member_completions() {
  777. if (member_completions.is_empty()) {
  778. for (const KeyValue<String, const LSP::DocumentSymbol *> &E : members) {
  779. const LSP::DocumentSymbol *symbol = E.value;
  780. LSP::CompletionItem item = symbol->make_completion_item();
  781. item.data = JOIN_SYMBOLS(path, E.key);
  782. member_completions.push_back(item.to_json());
  783. }
  784. for (const KeyValue<String, ClassMembers> &E : inner_classes) {
  785. const ClassMembers *inner_class = &E.value;
  786. for (const KeyValue<String, const LSP::DocumentSymbol *> &F : *inner_class) {
  787. const LSP::DocumentSymbol *symbol = F.value;
  788. LSP::CompletionItem item = symbol->make_completion_item();
  789. item.data = JOIN_SYMBOLS(path, JOIN_SYMBOLS(E.key, F.key));
  790. member_completions.push_back(item.to_json());
  791. }
  792. }
  793. }
  794. return member_completions;
  795. }
  796. Dictionary ExtendGDScriptParser::dump_function_api(const GDScriptParser::FunctionNode *p_func) const {
  797. ERR_FAIL_NULL_V(p_func, Dictionary());
  798. Dictionary func;
  799. func["name"] = p_func->identifier->name;
  800. func["return_type"] = p_func->get_datatype().to_string();
  801. func["rpc_config"] = p_func->rpc_config;
  802. Array parameters;
  803. for (int i = 0; i < p_func->parameters.size(); i++) {
  804. Dictionary arg;
  805. arg["name"] = p_func->parameters[i]->identifier->name;
  806. arg["type"] = p_func->parameters[i]->get_datatype().to_string();
  807. if (p_func->parameters[i]->initializer != nullptr) {
  808. arg["default_value"] = p_func->parameters[i]->initializer->reduced_value;
  809. }
  810. parameters.push_back(arg);
  811. }
  812. if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(p_func->start_line))) {
  813. func["signature"] = symbol->detail;
  814. func["description"] = symbol->documentation;
  815. }
  816. func["arguments"] = parameters;
  817. return func;
  818. }
  819. Dictionary ExtendGDScriptParser::dump_class_api(const GDScriptParser::ClassNode *p_class) const {
  820. ERR_FAIL_NULL_V(p_class, Dictionary());
  821. Dictionary class_api;
  822. class_api["name"] = p_class->identifier != nullptr ? String(p_class->identifier->name) : String();
  823. class_api["path"] = path;
  824. Array extends_class;
  825. for (int i = 0; i < p_class->extends.size(); i++) {
  826. extends_class.append(String(p_class->extends[i]->name));
  827. }
  828. class_api["extends_class"] = extends_class;
  829. class_api["extends_file"] = String(p_class->extends_path);
  830. class_api["icon"] = String(p_class->icon_path);
  831. if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(p_class->start_line))) {
  832. class_api["signature"] = symbol->detail;
  833. class_api["description"] = symbol->documentation;
  834. }
  835. Array nested_classes;
  836. Array constants;
  837. Array class_members;
  838. Array signals;
  839. Array methods;
  840. Array static_functions;
  841. for (int i = 0; i < p_class->members.size(); i++) {
  842. const ClassNode::Member &m = p_class->members[i];
  843. switch (m.type) {
  844. case ClassNode::Member::CLASS:
  845. nested_classes.push_back(dump_class_api(m.m_class));
  846. break;
  847. case ClassNode::Member::CONSTANT: {
  848. Dictionary api;
  849. api["name"] = m.constant->identifier->name;
  850. api["value"] = m.constant->initializer->reduced_value;
  851. api["data_type"] = m.constant->get_datatype().to_string();
  852. if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.constant->start_line))) {
  853. api["signature"] = symbol->detail;
  854. api["description"] = symbol->documentation;
  855. }
  856. constants.push_back(api);
  857. } break;
  858. case ClassNode::Member::ENUM_VALUE: {
  859. Dictionary api;
  860. api["name"] = m.enum_value.identifier->name;
  861. api["value"] = m.enum_value.value;
  862. api["data_type"] = m.get_datatype().to_string();
  863. if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.enum_value.line))) {
  864. api["signature"] = symbol->detail;
  865. api["description"] = symbol->documentation;
  866. }
  867. constants.push_back(api);
  868. } break;
  869. case ClassNode::Member::ENUM: {
  870. Dictionary enum_dict;
  871. for (int j = 0; j < m.m_enum->values.size(); j++) {
  872. enum_dict[m.m_enum->values[j].identifier->name] = m.m_enum->values[j].value;
  873. }
  874. Dictionary api;
  875. api["name"] = m.m_enum->identifier->name;
  876. api["value"] = enum_dict;
  877. api["data_type"] = m.get_datatype().to_string();
  878. if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.m_enum->start_line))) {
  879. api["signature"] = symbol->detail;
  880. api["description"] = symbol->documentation;
  881. }
  882. constants.push_back(api);
  883. } break;
  884. case ClassNode::Member::VARIABLE: {
  885. Dictionary api;
  886. api["name"] = m.variable->identifier->name;
  887. api["data_type"] = m.variable->get_datatype().to_string();
  888. api["default_value"] = m.variable->initializer != nullptr ? m.variable->initializer->reduced_value : Variant();
  889. api["setter"] = m.variable->setter ? ("@" + String(m.variable->identifier->name) + "_setter") : (m.variable->setter_pointer != nullptr ? String(m.variable->setter_pointer->name) : String());
  890. api["getter"] = m.variable->getter ? ("@" + String(m.variable->identifier->name) + "_getter") : (m.variable->getter_pointer != nullptr ? String(m.variable->getter_pointer->name) : String());
  891. api["export"] = m.variable->exported;
  892. if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.variable->start_line))) {
  893. api["signature"] = symbol->detail;
  894. api["description"] = symbol->documentation;
  895. }
  896. class_members.push_back(api);
  897. } break;
  898. case ClassNode::Member::SIGNAL: {
  899. Dictionary api;
  900. api["name"] = m.signal->identifier->name;
  901. Array pars;
  902. for (int j = 0; j < m.signal->parameters.size(); j++) {
  903. pars.append(String(m.signal->parameters[j]->identifier->name));
  904. }
  905. api["arguments"] = pars;
  906. if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.signal->start_line))) {
  907. api["signature"] = symbol->detail;
  908. api["description"] = symbol->documentation;
  909. }
  910. signals.push_back(api);
  911. } break;
  912. case ClassNode::Member::FUNCTION: {
  913. if (m.function->is_static) {
  914. static_functions.append(dump_function_api(m.function));
  915. } else {
  916. methods.append(dump_function_api(m.function));
  917. }
  918. } break;
  919. case ClassNode::Member::GROUP:
  920. break; // No-op, but silences warnings.
  921. case ClassNode::Member::UNDEFINED:
  922. break; // Unreachable.
  923. }
  924. }
  925. class_api["sub_classes"] = nested_classes;
  926. class_api["constants"] = constants;
  927. class_api["members"] = class_members;
  928. class_api["signals"] = signals;
  929. class_api["methods"] = methods;
  930. class_api["static_functions"] = static_functions;
  931. return class_api;
  932. }
  933. Dictionary ExtendGDScriptParser::generate_api() const {
  934. Dictionary api;
  935. if (const GDScriptParser::ClassNode *gdclass = dynamic_cast<const GDScriptParser::ClassNode *>(get_tree())) {
  936. api = dump_class_api(gdclass);
  937. }
  938. return api;
  939. }
  940. void ExtendGDScriptParser::parse(const String &p_code, const String &p_path) {
  941. path = p_path;
  942. lines = p_code.split("\n");
  943. parse_result = GDScriptParser::parse(p_code, p_path, false);
  944. GDScriptAnalyzer analyzer(this);
  945. if (parse_result == OK) {
  946. parse_result = analyzer.analyze();
  947. }
  948. update_diagnostics();
  949. update_symbols();
  950. update_document_links(p_code);
  951. }