gdscript_translation_parser_plugin.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. /**************************************************************************/
  2. /* gdscript_translation_parser_plugin.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_translation_parser_plugin.h"
  31. #include "../gdscript.h"
  32. #include "../gdscript_analyzer.h"
  33. #include "core/io/resource_loader.h"
  34. void GDScriptEditorTranslationParserPlugin::get_recognized_extensions(List<String> *r_extensions) const {
  35. GDScriptLanguage::get_singleton()->get_recognized_extensions(r_extensions);
  36. }
  37. Error GDScriptEditorTranslationParserPlugin::parse_file(const String &p_path, Vector<Vector<String>> *r_translations) {
  38. // Extract all translatable strings using the parsed tree from GDScriptParser.
  39. // The strategy is to find all ExpressionNode and AssignmentNode from the tree and extract strings if relevant, i.e
  40. // Search strings in ExpressionNode -> CallNode -> tr(), set_text(), set_placeholder() etc.
  41. // Search strings in AssignmentNode -> text = "__", tooltip_text = "__" etc.
  42. Error err;
  43. Ref<Resource> loaded_res = ResourceLoader::load(p_path, "", ResourceFormatLoader::CACHE_MODE_REUSE, &err);
  44. ERR_FAIL_COND_V_MSG(err, err, "Failed to load " + p_path);
  45. translations = r_translations;
  46. Ref<GDScript> gdscript = loaded_res;
  47. String source_code = gdscript->get_source_code();
  48. GDScriptParser parser;
  49. err = parser.parse(source_code, p_path, false);
  50. ERR_FAIL_COND_V_MSG(err, err, "Failed to parse GDScript with GDScriptParser.");
  51. GDScriptAnalyzer analyzer(&parser);
  52. err = analyzer.analyze();
  53. ERR_FAIL_COND_V_MSG(err, err, "Failed to analyze GDScript with GDScriptAnalyzer.");
  54. comment_data = &parser.comment_data;
  55. // Traverse through the parsed tree from GDScriptParser.
  56. GDScriptParser::ClassNode *c = parser.get_tree();
  57. _traverse_class(c);
  58. comment_data = nullptr;
  59. return OK;
  60. }
  61. bool GDScriptEditorTranslationParserPlugin::_is_constant_string(const GDScriptParser::ExpressionNode *p_expression) {
  62. ERR_FAIL_NULL_V(p_expression, false);
  63. return p_expression->is_constant && p_expression->reduced_value.is_string();
  64. }
  65. String GDScriptEditorTranslationParserPlugin::_parse_comment(int p_line, bool &r_skip) const {
  66. // Parse inline comment.
  67. if (comment_data->has(p_line)) {
  68. const String stripped_comment = comment_data->get(p_line).comment.trim_prefix("#").strip_edges();
  69. if (stripped_comment.begins_with("TRANSLATORS:")) {
  70. return stripped_comment.trim_prefix("TRANSLATORS:").strip_edges(true, false);
  71. }
  72. if (stripped_comment == "NO_TRANSLATE" || stripped_comment.begins_with("NO_TRANSLATE:")) {
  73. r_skip = true;
  74. return String();
  75. }
  76. }
  77. // Parse multiline comment.
  78. String multiline_comment;
  79. for (int line = p_line - 1; comment_data->has(line) && comment_data->get(line).new_line; line--) {
  80. const String stripped_comment = comment_data->get(line).comment.trim_prefix("#").strip_edges();
  81. if (stripped_comment.is_empty()) {
  82. continue;
  83. }
  84. if (multiline_comment.is_empty()) {
  85. multiline_comment = stripped_comment;
  86. } else {
  87. multiline_comment = stripped_comment + "\n" + multiline_comment;
  88. }
  89. if (stripped_comment.begins_with("TRANSLATORS:")) {
  90. return multiline_comment.trim_prefix("TRANSLATORS:").strip_edges(true, false);
  91. }
  92. if (stripped_comment == "NO_TRANSLATE" || stripped_comment.begins_with("NO_TRANSLATE:")) {
  93. r_skip = true;
  94. return String();
  95. }
  96. }
  97. return String();
  98. }
  99. void GDScriptEditorTranslationParserPlugin::_add_id(const String &p_id, int p_line) {
  100. bool skip = false;
  101. const String comment = _parse_comment(p_line, skip);
  102. if (skip) {
  103. return;
  104. }
  105. translations->push_back({ p_id, String(), String(), comment });
  106. }
  107. void GDScriptEditorTranslationParserPlugin::_add_id_ctx_plural(const Vector<String> &p_id_ctx_plural, int p_line) {
  108. bool skip = false;
  109. const String comment = _parse_comment(p_line, skip);
  110. if (skip) {
  111. return;
  112. }
  113. translations->push_back({ p_id_ctx_plural[0], p_id_ctx_plural[1], p_id_ctx_plural[2], comment });
  114. }
  115. void GDScriptEditorTranslationParserPlugin::_traverse_class(const GDScriptParser::ClassNode *p_class) {
  116. for (int i = 0; i < p_class->members.size(); i++) {
  117. const GDScriptParser::ClassNode::Member &m = p_class->members[i];
  118. // Other member types can't contain translatable strings.
  119. switch (m.type) {
  120. case GDScriptParser::ClassNode::Member::CLASS:
  121. _traverse_class(m.m_class);
  122. break;
  123. case GDScriptParser::ClassNode::Member::FUNCTION:
  124. _traverse_function(m.function);
  125. break;
  126. case GDScriptParser::ClassNode::Member::VARIABLE:
  127. _assess_expression(m.variable->initializer);
  128. if (m.variable->property == GDScriptParser::VariableNode::PROP_INLINE) {
  129. _traverse_function(m.variable->setter);
  130. _traverse_function(m.variable->getter);
  131. }
  132. break;
  133. default:
  134. break;
  135. }
  136. }
  137. }
  138. void GDScriptEditorTranslationParserPlugin::_traverse_function(const GDScriptParser::FunctionNode *p_func) {
  139. if (!p_func) {
  140. return;
  141. }
  142. for (int i = 0; i < p_func->parameters.size(); i++) {
  143. _assess_expression(p_func->parameters[i]->initializer);
  144. }
  145. _traverse_block(p_func->body);
  146. }
  147. void GDScriptEditorTranslationParserPlugin::_traverse_block(const GDScriptParser::SuiteNode *p_suite) {
  148. if (!p_suite) {
  149. return;
  150. }
  151. const Vector<GDScriptParser::Node *> &statements = p_suite->statements;
  152. for (int i = 0; i < statements.size(); i++) {
  153. const GDScriptParser::Node *statement = statements[i];
  154. // BREAK, BREAKPOINT, CONSTANT, CONTINUE, and PASS are skipped because they can't contain translatable strings.
  155. switch (statement->type) {
  156. case GDScriptParser::Node::ASSERT: {
  157. const GDScriptParser::AssertNode *assert_node = static_cast<const GDScriptParser::AssertNode *>(statement);
  158. _assess_expression(assert_node->condition);
  159. _assess_expression(assert_node->message);
  160. } break;
  161. case GDScriptParser::Node::ASSIGNMENT: {
  162. _assess_assignment(static_cast<const GDScriptParser::AssignmentNode *>(statement));
  163. } break;
  164. case GDScriptParser::Node::FOR: {
  165. const GDScriptParser::ForNode *for_node = static_cast<const GDScriptParser::ForNode *>(statement);
  166. _assess_expression(for_node->list);
  167. _traverse_block(for_node->loop);
  168. } break;
  169. case GDScriptParser::Node::IF: {
  170. const GDScriptParser::IfNode *if_node = static_cast<const GDScriptParser::IfNode *>(statement);
  171. _assess_expression(if_node->condition);
  172. _traverse_block(if_node->true_block);
  173. _traverse_block(if_node->false_block);
  174. } break;
  175. case GDScriptParser::Node::MATCH: {
  176. const GDScriptParser::MatchNode *match_node = static_cast<const GDScriptParser::MatchNode *>(statement);
  177. _assess_expression(match_node->test);
  178. for (int j = 0; j < match_node->branches.size(); j++) {
  179. _traverse_block(match_node->branches[j]->guard_body);
  180. _traverse_block(match_node->branches[j]->block);
  181. }
  182. } break;
  183. case GDScriptParser::Node::RETURN: {
  184. _assess_expression(static_cast<const GDScriptParser::ReturnNode *>(statement)->return_value);
  185. } break;
  186. case GDScriptParser::Node::VARIABLE: {
  187. _assess_expression(static_cast<const GDScriptParser::VariableNode *>(statement)->initializer);
  188. } break;
  189. case GDScriptParser::Node::WHILE: {
  190. const GDScriptParser::WhileNode *while_node = static_cast<const GDScriptParser::WhileNode *>(statement);
  191. _assess_expression(while_node->condition);
  192. _traverse_block(while_node->loop);
  193. } break;
  194. default: {
  195. if (statement->is_expression()) {
  196. _assess_expression(static_cast<const GDScriptParser::ExpressionNode *>(statement));
  197. }
  198. } break;
  199. }
  200. }
  201. }
  202. void GDScriptEditorTranslationParserPlugin::_assess_expression(const GDScriptParser::ExpressionNode *p_expression) {
  203. // Explore all ExpressionNodes to find CallNodes which contain translation strings, such as tr(), set_text() etc.
  204. // tr() can be embedded quite deep within multiple ExpressionNodes so need to dig down to search through all ExpressionNodes.
  205. if (!p_expression) {
  206. return;
  207. }
  208. // GET_NODE, IDENTIFIER, LITERAL, PRELOAD, SELF, and TYPE are skipped because they can't contain translatable strings.
  209. switch (p_expression->type) {
  210. case GDScriptParser::Node::ARRAY: {
  211. const GDScriptParser::ArrayNode *array_node = static_cast<const GDScriptParser::ArrayNode *>(p_expression);
  212. for (int i = 0; i < array_node->elements.size(); i++) {
  213. _assess_expression(array_node->elements[i]);
  214. }
  215. } break;
  216. case GDScriptParser::Node::ASSIGNMENT: {
  217. _assess_assignment(static_cast<const GDScriptParser::AssignmentNode *>(p_expression));
  218. } break;
  219. case GDScriptParser::Node::AWAIT: {
  220. _assess_expression(static_cast<const GDScriptParser::AwaitNode *>(p_expression)->to_await);
  221. } break;
  222. case GDScriptParser::Node::BINARY_OPERATOR: {
  223. const GDScriptParser::BinaryOpNode *binary_op_node = static_cast<const GDScriptParser::BinaryOpNode *>(p_expression);
  224. _assess_expression(binary_op_node->left_operand);
  225. _assess_expression(binary_op_node->right_operand);
  226. } break;
  227. case GDScriptParser::Node::CALL: {
  228. _assess_call(static_cast<const GDScriptParser::CallNode *>(p_expression));
  229. } break;
  230. case GDScriptParser::Node::CAST: {
  231. _assess_expression(static_cast<const GDScriptParser::CastNode *>(p_expression)->operand);
  232. } break;
  233. case GDScriptParser::Node::DICTIONARY: {
  234. const GDScriptParser::DictionaryNode *dict_node = static_cast<const GDScriptParser::DictionaryNode *>(p_expression);
  235. for (int i = 0; i < dict_node->elements.size(); i++) {
  236. _assess_expression(dict_node->elements[i].key);
  237. _assess_expression(dict_node->elements[i].value);
  238. }
  239. } break;
  240. case GDScriptParser::Node::LAMBDA: {
  241. _traverse_function(static_cast<const GDScriptParser::LambdaNode *>(p_expression)->function);
  242. } break;
  243. case GDScriptParser::Node::SUBSCRIPT: {
  244. const GDScriptParser::SubscriptNode *subscript_node = static_cast<const GDScriptParser::SubscriptNode *>(p_expression);
  245. _assess_expression(subscript_node->base);
  246. if (!subscript_node->is_attribute) {
  247. _assess_expression(subscript_node->index);
  248. }
  249. } break;
  250. case GDScriptParser::Node::TERNARY_OPERATOR: {
  251. const GDScriptParser::TernaryOpNode *ternary_op_node = static_cast<const GDScriptParser::TernaryOpNode *>(p_expression);
  252. _assess_expression(ternary_op_node->condition);
  253. _assess_expression(ternary_op_node->true_expr);
  254. _assess_expression(ternary_op_node->false_expr);
  255. } break;
  256. case GDScriptParser::Node::TYPE_TEST: {
  257. _assess_expression(static_cast<const GDScriptParser::TypeTestNode *>(p_expression)->operand);
  258. } break;
  259. case GDScriptParser::Node::UNARY_OPERATOR: {
  260. _assess_expression(static_cast<const GDScriptParser::UnaryOpNode *>(p_expression)->operand);
  261. } break;
  262. default: {
  263. } break;
  264. }
  265. }
  266. void GDScriptEditorTranslationParserPlugin::_assess_assignment(const GDScriptParser::AssignmentNode *p_assignment) {
  267. _assess_expression(p_assignment->assignee);
  268. _assess_expression(p_assignment->assigned_value);
  269. // Extract the translatable strings coming from assignments. For example, get_node("Label").text = "____"
  270. StringName assignee_name;
  271. if (p_assignment->assignee->type == GDScriptParser::Node::IDENTIFIER) {
  272. assignee_name = static_cast<const GDScriptParser::IdentifierNode *>(p_assignment->assignee)->name;
  273. } else if (p_assignment->assignee->type == GDScriptParser::Node::SUBSCRIPT) {
  274. const GDScriptParser::SubscriptNode *subscript = static_cast<const GDScriptParser::SubscriptNode *>(p_assignment->assignee);
  275. if (subscript->is_attribute && subscript->attribute) {
  276. assignee_name = subscript->attribute->name;
  277. } else if (subscript->index && _is_constant_string(subscript->index)) {
  278. assignee_name = subscript->index->reduced_value;
  279. }
  280. }
  281. if (assignee_name != StringName() && assignment_patterns.has(assignee_name) && _is_constant_string(p_assignment->assigned_value)) {
  282. // If the assignment is towards one of the extract patterns (text, tooltip_text etc.), and the value is a constant string, we collect the string.
  283. _add_id(p_assignment->assigned_value->reduced_value, p_assignment->assigned_value->start_line);
  284. } else if (assignee_name == fd_filters) {
  285. // Extract from `get_node("FileDialog").filters = <filter array>`.
  286. _extract_fd_filter_array(p_assignment->assigned_value);
  287. }
  288. }
  289. void GDScriptEditorTranslationParserPlugin::_assess_call(const GDScriptParser::CallNode *p_call) {
  290. _assess_expression(p_call->callee);
  291. for (int i = 0; i < p_call->arguments.size(); i++) {
  292. _assess_expression(p_call->arguments[i]);
  293. }
  294. // Extract the translatable strings coming from function calls. For example:
  295. // tr("___"), get_node("Label").set_text("____"), get_node("LineEdit").set_placeholder("____").
  296. StringName function_name = p_call->function_name;
  297. // Variables for extracting tr() and tr_n().
  298. Vector<String> id_ctx_plural;
  299. id_ctx_plural.resize(3);
  300. bool extract_id_ctx_plural = true;
  301. if (function_name == tr_func || function_name == atr_func) {
  302. // Extract from `tr(id, ctx)` or `atr(id, ctx)`.
  303. for (int i = 0; i < p_call->arguments.size(); i++) {
  304. if (_is_constant_string(p_call->arguments[i])) {
  305. id_ctx_plural.write[i] = p_call->arguments[i]->reduced_value;
  306. } else {
  307. // Avoid adding something like tr("Flying dragon", var_context_level_1). We want to extract both id and context together.
  308. extract_id_ctx_plural = false;
  309. }
  310. }
  311. if (extract_id_ctx_plural) {
  312. _add_id_ctx_plural(id_ctx_plural, p_call->start_line);
  313. }
  314. } else if (function_name == trn_func || function_name == atrn_func) {
  315. // Extract from `tr_n(id, plural, n, ctx)` or `atr_n(id, plural, n, ctx)`.
  316. Vector<int> indices;
  317. indices.push_back(0);
  318. indices.push_back(3);
  319. indices.push_back(1);
  320. for (int i = 0; i < indices.size(); i++) {
  321. if (indices[i] >= p_call->arguments.size()) {
  322. continue;
  323. }
  324. if (_is_constant_string(p_call->arguments[indices[i]])) {
  325. id_ctx_plural.write[i] = p_call->arguments[indices[i]]->reduced_value;
  326. } else {
  327. extract_id_ctx_plural = false;
  328. }
  329. }
  330. if (extract_id_ctx_plural) {
  331. _add_id_ctx_plural(id_ctx_plural, p_call->start_line);
  332. }
  333. } else if (first_arg_patterns.has(function_name)) {
  334. if (!p_call->arguments.is_empty() && _is_constant_string(p_call->arguments[0])) {
  335. _add_id(p_call->arguments[0]->reduced_value, p_call->arguments[0]->start_line);
  336. }
  337. } else if (second_arg_patterns.has(function_name)) {
  338. if (p_call->arguments.size() > 1 && _is_constant_string(p_call->arguments[1])) {
  339. _add_id(p_call->arguments[1]->reduced_value, p_call->arguments[1]->start_line);
  340. }
  341. } else if (function_name == fd_add_filter) {
  342. // Extract the 'JPE Images' in this example - get_node("FileDialog").add_filter("*.jpg; JPE Images").
  343. if (!p_call->arguments.is_empty()) {
  344. _extract_fd_filter_string(p_call->arguments[0], p_call->arguments[0]->start_line);
  345. }
  346. } else if (function_name == fd_set_filter) {
  347. // Extract from `get_node("FileDialog").set_filters(<filter array>)`.
  348. if (!p_call->arguments.is_empty()) {
  349. _extract_fd_filter_array(p_call->arguments[0]);
  350. }
  351. }
  352. }
  353. void GDScriptEditorTranslationParserPlugin::_extract_fd_filter_string(const GDScriptParser::ExpressionNode *p_expression, int p_line) {
  354. // Extract the name in "extension ; name".
  355. if (_is_constant_string(p_expression)) {
  356. PackedStringArray arr = p_expression->reduced_value.operator String().split(";", true);
  357. ERR_FAIL_COND_MSG(arr.size() != 2, "Argument for setting FileDialog has bad format.");
  358. _add_id(arr[1].strip_edges(), p_line);
  359. }
  360. }
  361. void GDScriptEditorTranslationParserPlugin::_extract_fd_filter_array(const GDScriptParser::ExpressionNode *p_expression) {
  362. const GDScriptParser::ArrayNode *array_node = nullptr;
  363. if (p_expression->type == GDScriptParser::Node::ARRAY) {
  364. // Extract from `["*.png ; PNG Images","*.gd ; GDScript Files"]` (implicit cast to `PackedStringArray`).
  365. array_node = static_cast<const GDScriptParser::ArrayNode *>(p_expression);
  366. } else if (p_expression->type == GDScriptParser::Node::CALL) {
  367. // Extract from `PackedStringArray(["*.png ; PNG Images","*.gd ; GDScript Files"])`.
  368. const GDScriptParser::CallNode *call_node = static_cast<const GDScriptParser::CallNode *>(p_expression);
  369. if (call_node->get_callee_type() == GDScriptParser::Node::IDENTIFIER && call_node->function_name == SNAME("PackedStringArray") && !call_node->arguments.is_empty() && call_node->arguments[0]->type == GDScriptParser::Node::ARRAY) {
  370. array_node = static_cast<const GDScriptParser::ArrayNode *>(call_node->arguments[0]);
  371. }
  372. }
  373. if (array_node) {
  374. for (int i = 0; i < array_node->elements.size(); i++) {
  375. _extract_fd_filter_string(array_node->elements[i], array_node->elements[i]->start_line);
  376. }
  377. }
  378. }
  379. GDScriptEditorTranslationParserPlugin::GDScriptEditorTranslationParserPlugin() {
  380. assignment_patterns.insert("text");
  381. assignment_patterns.insert("placeholder_text");
  382. assignment_patterns.insert("tooltip_text");
  383. first_arg_patterns.insert("set_text");
  384. first_arg_patterns.insert("set_tooltip_text");
  385. first_arg_patterns.insert("set_placeholder");
  386. first_arg_patterns.insert("add_tab");
  387. first_arg_patterns.insert("add_check_item");
  388. first_arg_patterns.insert("add_item");
  389. first_arg_patterns.insert("add_multistate_item");
  390. first_arg_patterns.insert("add_radio_check_item");
  391. first_arg_patterns.insert("add_separator");
  392. first_arg_patterns.insert("add_submenu_item");
  393. second_arg_patterns.insert("set_tab_title");
  394. second_arg_patterns.insert("add_icon_check_item");
  395. second_arg_patterns.insert("add_icon_item");
  396. second_arg_patterns.insert("add_icon_radio_check_item");
  397. second_arg_patterns.insert("set_item_text");
  398. }