gdscript_translation_parser_plugin.cpp 17 KB

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