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