gdscript_highlighter.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  1. /**************************************************************************/
  2. /* gdscript_highlighter.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_highlighter.h"
  31. #include "../gdscript.h"
  32. #include "../gdscript_tokenizer.h"
  33. #include "core/config/project_settings.h"
  34. #include "core/core_constants.h"
  35. #include "editor/settings/editor_settings.h"
  36. #include "editor/themes/editor_theme_manager.h"
  37. #include "scene/gui/text_edit.h"
  38. Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_line) {
  39. Dictionary color_map;
  40. Type next_type = NONE;
  41. Type current_type = NONE;
  42. Type prev_type = NONE;
  43. String prev_text = "";
  44. int prev_column = 0;
  45. bool prev_is_char = false;
  46. bool prev_is_digit = false;
  47. bool prev_is_binary_op = false;
  48. bool in_keyword = false;
  49. bool in_word = false;
  50. bool in_number = false;
  51. bool in_node_path = false;
  52. bool in_node_ref = false;
  53. bool in_annotation = false;
  54. bool in_string_name = false;
  55. bool is_hex_notation = false;
  56. bool is_bin_notation = false;
  57. bool in_member_variable = false;
  58. bool in_lambda = false;
  59. bool in_function_name = false; // Any call.
  60. bool in_function_declaration = false; // Only declaration.
  61. bool in_signal_declaration = false;
  62. bool is_after_func_signal_declaration = false;
  63. bool in_var_const_declaration = false;
  64. bool is_after_var_const_declaration = false;
  65. bool expect_type = false;
  66. int in_declaration_params = 0; // The number of opened `(` after func/signal name.
  67. int in_declaration_param_dicts = 0; // The number of opened `{` inside func params.
  68. int in_type_params = 0; // The number of opened `[` after type name.
  69. Color keyword_color;
  70. Color color;
  71. color_region_cache[p_line] = -1;
  72. int in_region = -1;
  73. if (p_line != 0) {
  74. int prev_region_line = p_line - 1;
  75. while (prev_region_line > 0 && !color_region_cache.has(prev_region_line)) {
  76. prev_region_line--;
  77. }
  78. for (int i = prev_region_line; i < p_line - 1; i++) {
  79. get_line_syntax_highlighting(i);
  80. }
  81. if (!color_region_cache.has(p_line - 1)) {
  82. get_line_syntax_highlighting(p_line - 1);
  83. }
  84. in_region = color_region_cache[p_line - 1];
  85. }
  86. const String &str = text_edit->get_line_with_ime(p_line);
  87. const int line_length = str.length();
  88. Color prev_color;
  89. if (in_region != -1 && line_length == 0) {
  90. color_region_cache[p_line] = in_region;
  91. }
  92. for (int j = 0; j < line_length; j++) {
  93. Dictionary highlighter_info;
  94. color = font_color;
  95. bool is_char = !is_symbol(str[j]);
  96. bool is_a_symbol = is_symbol(str[j]);
  97. bool is_a_digit = is_digit(str[j]);
  98. bool is_binary_op = false;
  99. /* color regions */
  100. if (is_a_symbol || in_region != -1) {
  101. int from = j;
  102. if (in_region == -1) {
  103. for (; from < line_length; from++) {
  104. if (str[from] == '\\') {
  105. from++;
  106. continue;
  107. }
  108. break;
  109. }
  110. }
  111. if (from != line_length) {
  112. // Check if we are in entering a region.
  113. if (in_region == -1) {
  114. const bool r_prefix = from > 0 && str[from - 1] == 'r';
  115. for (int c = 0; c < color_regions.size(); c++) {
  116. // Check there is enough room.
  117. int chars_left = line_length - from;
  118. int start_key_length = color_regions[c].start_key.length();
  119. int end_key_length = color_regions[c].end_key.length();
  120. if (chars_left < start_key_length) {
  121. continue;
  122. }
  123. if (color_regions[c].is_string && color_regions[c].r_prefix != r_prefix) {
  124. continue;
  125. }
  126. // Search the line.
  127. bool match = true;
  128. const char32_t *start_key = color_regions[c].start_key.get_data();
  129. for (int k = 0; k < start_key_length; k++) {
  130. if (start_key[k] != str[from + k]) {
  131. match = false;
  132. break;
  133. }
  134. }
  135. // "#region" and "#endregion" only highlighted if they're the first region on the line.
  136. if (color_regions[c].type == ColorRegion::TYPE_CODE_REGION) {
  137. Vector<String> str_stripped_split = str.strip_edges().split_spaces(1);
  138. if (!str_stripped_split.is_empty() &&
  139. str_stripped_split[0] != "#region" &&
  140. str_stripped_split[0] != "#endregion") {
  141. match = false;
  142. }
  143. }
  144. if (!match) {
  145. continue;
  146. }
  147. in_region = c;
  148. from += start_key_length;
  149. // Check if it's the whole line.
  150. if (end_key_length == 0 || color_regions[c].line_only || from + end_key_length > line_length) {
  151. // Don't skip comments, for highlighting markers.
  152. if (color_regions[in_region].is_comment) {
  153. break;
  154. }
  155. if (from + end_key_length > line_length) {
  156. // If it's key length and there is a '\', dont skip to highlight esc chars.
  157. if (str.find_char('\\', from) >= 0) {
  158. break;
  159. }
  160. }
  161. prev_color = color_regions[in_region].color;
  162. highlighter_info["color"] = color_regions[c].color;
  163. color_map[j] = highlighter_info;
  164. j = line_length;
  165. if (!color_regions[c].line_only) {
  166. color_region_cache[p_line] = c;
  167. }
  168. }
  169. break;
  170. }
  171. // Don't skip comments, for highlighting markers.
  172. if (j == line_length && !color_regions[in_region].is_comment) {
  173. continue;
  174. }
  175. }
  176. // If we are in one, find the end key.
  177. if (in_region != -1) {
  178. Color region_color = color_regions[in_region].color;
  179. if (in_node_path && color_regions[in_region].type == ColorRegion::TYPE_STRING) {
  180. region_color = node_path_color;
  181. }
  182. if (in_node_ref && color_regions[in_region].type == ColorRegion::TYPE_STRING) {
  183. region_color = node_ref_color;
  184. }
  185. if (in_string_name && color_regions[in_region].type == ColorRegion::TYPE_STRING) {
  186. region_color = string_name_color;
  187. }
  188. prev_color = region_color;
  189. highlighter_info["color"] = region_color;
  190. color_map[j] = highlighter_info;
  191. if (color_regions[in_region].is_comment) {
  192. int marker_start_pos = from;
  193. int marker_len = 0;
  194. while (from <= line_length) {
  195. if (from < line_length && is_unicode_identifier_continue(str[from])) {
  196. marker_len++;
  197. } else {
  198. if (marker_len > 0) {
  199. HashMap<String, CommentMarkerLevel>::ConstIterator E = comment_markers.find(str.substr(marker_start_pos, marker_len));
  200. if (E) {
  201. Dictionary marker_highlighter_info;
  202. marker_highlighter_info["color"] = comment_marker_colors[E->value];
  203. color_map[marker_start_pos] = marker_highlighter_info;
  204. Dictionary marker_continue_highlighter_info;
  205. marker_continue_highlighter_info["color"] = region_color;
  206. color_map[from] = marker_continue_highlighter_info;
  207. }
  208. }
  209. marker_start_pos = from + 1;
  210. marker_len = 0;
  211. }
  212. from++;
  213. }
  214. from = line_length - 1;
  215. j = from;
  216. } else {
  217. // Search the line.
  218. int region_end_index = -1;
  219. int end_key_length = color_regions[in_region].end_key.length();
  220. const char32_t *end_key = color_regions[in_region].end_key.get_data();
  221. int placeholder_end = from;
  222. for (; from < line_length; from++) {
  223. if (line_length - from < end_key_length) {
  224. // Don't break if '\' to highlight escape sequences,
  225. // and '%' and '{' to highlight placeholders.
  226. if (str.find_char('\\', from) == -1 && str.find_char('%', from) == -1 && str.find_char('{', from) == -1) {
  227. break;
  228. }
  229. }
  230. if (!is_symbol(str[from]) && str[from] != '%') {
  231. continue;
  232. }
  233. if (str[from] == '%' || str[from] == '{') {
  234. int placeholder_start = from;
  235. bool is_percent = str[from] == '%';
  236. from++;
  237. if (is_percent) {
  238. if (str[from] == '%') {
  239. placeholder_end = from + 1;
  240. } else {
  241. const String allowed_chars = "+.-*0123456789";
  242. const String placeholder_types = "cdfosvxX";
  243. for (int i = 0; i < line_length - from; i++) {
  244. if (allowed_chars.contains_char(str[from + i]) &&
  245. !placeholder_types.contains_char(str[from + i]) &&
  246. (str[from + i] != end_key[0] || (str[from + i] == end_key[0] && str[from + i - 1] == '\\'))) {
  247. continue;
  248. }
  249. if (placeholder_types.contains_char(str[from + i])) {
  250. placeholder_end = from + i + 1;
  251. }
  252. break;
  253. }
  254. }
  255. } else {
  256. for (int i = 0; i < line_length - from; i++) {
  257. if (str[from + i] != '}' && (str[from + i] != end_key[0] || (str[from + i] == end_key[0] && str[from + i - 1] == '\\'))) {
  258. continue;
  259. }
  260. if (str[from + i] == '}') {
  261. placeholder_end = from + i + 1;
  262. }
  263. break;
  264. }
  265. }
  266. if (placeholder_end > placeholder_start) {
  267. Dictionary placeholder_highlighter_info;
  268. placeholder_highlighter_info["color"] = placeholder_color;
  269. color_map[placeholder_start] = placeholder_highlighter_info;
  270. Dictionary region_continue_highlighter_info;
  271. region_continue_highlighter_info["color"] = region_color;
  272. color_map[placeholder_end] = region_continue_highlighter_info;
  273. }
  274. }
  275. if (str[from] == '\\') {
  276. if (!color_regions[in_region].r_prefix) {
  277. Dictionary escape_char_highlighter_info;
  278. escape_char_highlighter_info["color"] = symbol_color;
  279. color_map[from] = escape_char_highlighter_info;
  280. }
  281. from++;
  282. if (!color_regions[in_region].r_prefix) {
  283. int esc_len = 0;
  284. if (str[from] == 'u') {
  285. esc_len = 4;
  286. } else if (str[from] == 'U') {
  287. esc_len = 6;
  288. }
  289. for (int k = 0; k < esc_len && from < line_length - 1; k++) {
  290. if (!is_hex_digit(str[from + 1])) {
  291. break;
  292. }
  293. from++;
  294. }
  295. Dictionary region_continue_highlighter_info;
  296. region_continue_highlighter_info["color"] = from < placeholder_end ? placeholder_color : region_color;
  297. color_map[from + 1] = region_continue_highlighter_info;
  298. }
  299. continue;
  300. }
  301. region_end_index = from;
  302. for (int k = 0; k < end_key_length; k++) {
  303. if (end_key[k] != str[from + k]) {
  304. region_end_index = -1;
  305. break;
  306. }
  307. }
  308. if (region_end_index != -1) {
  309. break;
  310. }
  311. }
  312. j = from + (end_key_length - 1);
  313. if (region_end_index == -1) {
  314. color_region_cache[p_line] = in_region;
  315. }
  316. }
  317. prev_type = REGION;
  318. prev_text = "";
  319. prev_column = j;
  320. in_region = -1;
  321. prev_is_char = false;
  322. prev_is_digit = false;
  323. prev_is_binary_op = false;
  324. continue;
  325. }
  326. color_map.sort(); // Prevents e.g. escape sequences from being overridden by string placeholders.
  327. }
  328. }
  329. // VERY hacky... but couldn't come up with anything better.
  330. if (j > 0 && (str[j] == '&' || str[j] == '^' || str[j] == '%' || str[j] == '+' || str[j] == '-' || str[j] == '~' || str[j] == '.')) {
  331. int to = j - 1;
  332. // Find what the last text was (prev_text won't work if there's no whitespace, so we need to do it manually).
  333. while (to > 0 && is_whitespace(str[to])) {
  334. to--;
  335. }
  336. int from = to;
  337. while (from > 0 && !is_symbol(str[from])) {
  338. from--;
  339. }
  340. String word = str.substr(from + 1, to - from);
  341. // Keywords need to be exceptions, except for keywords that represent a value.
  342. if (word == "true" || word == "false" || word == "null" || word == "PI" || word == "TAU" || word == "INF" || word == "NAN" || word == "self" || word == "super" || !reserved_keywords.has(word)) {
  343. if (!is_symbol(str[to]) || str[to] == '"' || str[to] == '\'' || str[to] == ')' || str[to] == ']' || str[to] == '}') {
  344. is_binary_op = true;
  345. }
  346. }
  347. }
  348. if (!is_char) {
  349. in_keyword = false;
  350. }
  351. // Allow ABCDEF in hex notation.
  352. if (is_hex_notation && (is_hex_digit(str[j]) || is_a_digit)) {
  353. is_a_digit = true;
  354. } else if (str[j] != '_') {
  355. is_hex_notation = false;
  356. }
  357. // Disallow anything not a 0 or 1 in binary notation.
  358. if (is_bin_notation && !is_binary_digit(str[j])) {
  359. is_a_digit = false;
  360. is_bin_notation = false;
  361. }
  362. if (!in_number && !in_word && is_a_digit) {
  363. in_number = true;
  364. }
  365. // Special cases for numbers.
  366. if (in_number && !is_a_digit) {
  367. if ((str[j] == 'b' || str[j] == 'B') && str[j - 1] == '0') {
  368. is_bin_notation = true;
  369. } else if ((str[j] == 'x' || str[j] == 'X') && str[j - 1] == '0') {
  370. is_hex_notation = true;
  371. } else if (!((str[j] == '-' || str[j] == '+') && (str[j - 1] == 'e' || str[j - 1] == 'E') && !prev_is_digit) &&
  372. !(str[j] == '_' && (prev_is_digit || str[j - 1] == 'b' || str[j - 1] == 'B' || str[j - 1] == 'x' || str[j - 1] == 'X' || str[j - 1] == '.')) &&
  373. !((str[j] == 'e' || str[j] == 'E') && (prev_is_digit || str[j - 1] == '_')) &&
  374. !(str[j] == '.' && (prev_is_digit || (!prev_is_binary_op && (j > 0 && (str[j - 1] == '_' || str[j - 1] == '-' || str[j - 1] == '+' || str[j - 1] == '~'))))) &&
  375. !((str[j] == '-' || str[j] == '+' || str[j] == '~') && !is_binary_op && !prev_is_binary_op && str[j - 1] != 'e' && str[j - 1] != 'E')) {
  376. /* This condition continues number highlighting in special cases.
  377. 1st row: '+' or '-' after scientific notation (like 3e-4);
  378. 2nd row: '_' as a numeric separator;
  379. 3rd row: Scientific notation 'e' and floating points;
  380. 4th row: Floating points inside the number, or leading if after a unary mathematical operator;
  381. 5th row: Multiple unary mathematical operators (like ~-7) */
  382. in_number = false;
  383. }
  384. } else if (str[j] == '.' && !is_binary_op && is_digit(str[j + 1]) && (j == 0 || (j > 0 && str[j - 1] != '.'))) {
  385. // Start number highlighting from leading decimal points (like .42)
  386. in_number = true;
  387. } else if ((str[j] == '-' || str[j] == '+' || str[j] == '~') && !is_binary_op) {
  388. // Only start number highlighting on unary operators if a digit follows them.
  389. int non_op = j + 1;
  390. while (str[non_op] == '-' || str[non_op] == '+' || str[non_op] == '~') {
  391. non_op++;
  392. }
  393. if (is_digit(str[non_op]) || (str[non_op] == '.' && non_op < line_length && is_digit(str[non_op + 1]))) {
  394. in_number = true;
  395. }
  396. }
  397. if (!in_word && is_unicode_identifier_start(str[j]) && !in_number) {
  398. in_word = true;
  399. }
  400. if (is_a_symbol && str[j] != '.' && in_word) {
  401. in_word = false;
  402. }
  403. if (!in_keyword && is_char && !prev_is_char) {
  404. int to = j;
  405. while (to < line_length && !is_symbol(str[to])) {
  406. to++;
  407. }
  408. String word = str.substr(j, to - j);
  409. Color col;
  410. if (global_functions.has(word)) {
  411. // "assert" and "preload" are reserved, so highlight even if not followed by a bracket.
  412. if (word == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::ASSERT) || word == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::PRELOAD)) {
  413. col = global_function_color;
  414. } else {
  415. // For other global functions, check if followed by bracket.
  416. int k = to;
  417. while (k < line_length && is_whitespace(str[k])) {
  418. k++;
  419. }
  420. if (str[k] == '(') {
  421. col = global_function_color;
  422. }
  423. }
  424. } else if (class_names.has(word)) {
  425. col = class_names[word];
  426. } else if (reserved_keywords.has(word)) {
  427. col = reserved_keywords[word];
  428. // Don't highlight `list` as a type in `for elem: Type in list`.
  429. expect_type = false;
  430. } else if (member_keywords.has(word)) {
  431. col = member_keywords[word];
  432. in_member_variable = true;
  433. }
  434. if (col != Color()) {
  435. for (int k = j - 1; k >= 0; k--) {
  436. if (str[k] == '.') {
  437. // Keyword, member, & global func indexing not allowed,
  438. // but don't reset color if prev was a number like "5."
  439. col = (prev_type == NUMBER) ? col : Color();
  440. break;
  441. } else if (str[k] > 32) {
  442. break;
  443. }
  444. }
  445. if (!in_member_variable && col != Color()) {
  446. in_keyword = true;
  447. keyword_color = col;
  448. }
  449. }
  450. }
  451. if (!in_function_name && in_word && !in_keyword) {
  452. if (prev_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::SIGNAL)) {
  453. in_signal_declaration = true;
  454. } else {
  455. int k = j;
  456. while (k < line_length && !is_symbol(str[k]) && !is_whitespace(str[k])) {
  457. k++;
  458. }
  459. // Check for space between name and bracket.
  460. while (k < line_length && is_whitespace(str[k])) {
  461. k++;
  462. }
  463. if (str[k] == '(') {
  464. in_function_name = true;
  465. if (prev_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::FUNC)) {
  466. in_function_declaration = true;
  467. }
  468. } else if (prev_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::VAR) || prev_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::FOR) || prev_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::TK_CONST)) {
  469. in_var_const_declaration = true;
  470. }
  471. // Check for lambda.
  472. if (in_function_declaration) {
  473. k = j - 1;
  474. while (k > 0 && is_whitespace(str[k])) {
  475. k--;
  476. }
  477. if (str[k] == ':') {
  478. in_lambda = true;
  479. }
  480. }
  481. }
  482. }
  483. if (!in_function_name && !in_member_variable && !in_keyword && !in_number && in_word) {
  484. int k = j;
  485. while (k > 0 && !is_symbol(str[k]) && !is_whitespace(str[k])) {
  486. k--;
  487. }
  488. if (str[k] == '.' && (k < 1 || str[k - 1] != '.')) {
  489. in_member_variable = true;
  490. }
  491. }
  492. if (is_a_symbol) {
  493. if (in_function_declaration || in_signal_declaration) {
  494. is_after_func_signal_declaration = true;
  495. }
  496. if (in_var_const_declaration) {
  497. is_after_var_const_declaration = true;
  498. }
  499. if (in_declaration_params > 0) {
  500. switch (str[j]) {
  501. case '(':
  502. in_declaration_params += 1;
  503. break;
  504. case ')':
  505. in_declaration_params -= 1;
  506. break;
  507. case '{':
  508. in_declaration_param_dicts += 1;
  509. break;
  510. case '}':
  511. in_declaration_param_dicts -= 1;
  512. break;
  513. }
  514. } else if ((is_after_func_signal_declaration || prev_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::FUNC)) && str[j] == '(') {
  515. in_declaration_params = 1;
  516. in_declaration_param_dicts = 0;
  517. }
  518. if (expect_type) {
  519. switch (str[j]) {
  520. case '[':
  521. in_type_params += 1;
  522. break;
  523. case ']':
  524. in_type_params -= 1;
  525. break;
  526. case ',':
  527. if (in_type_params <= 0) {
  528. expect_type = false;
  529. }
  530. break;
  531. case ' ':
  532. case '\t':
  533. case '.':
  534. break;
  535. default:
  536. expect_type = false;
  537. break;
  538. }
  539. } else {
  540. if (j > 0 && str[j - 1] == '-' && str[j] == '>') {
  541. expect_type = true;
  542. in_type_params = 0;
  543. }
  544. if ((is_after_var_const_declaration || (in_declaration_params == 1 && in_declaration_param_dicts == 0)) && str[j] == ':') {
  545. expect_type = true;
  546. in_type_params = 0;
  547. }
  548. }
  549. in_function_name = false;
  550. in_function_declaration = false;
  551. in_signal_declaration = false;
  552. in_var_const_declaration = false;
  553. in_lambda = false;
  554. in_member_variable = false;
  555. if (!is_whitespace(str[j])) {
  556. is_after_func_signal_declaration = false;
  557. is_after_var_const_declaration = false;
  558. }
  559. }
  560. // Set color of StringName, keeping symbol color for binary '&&' and '&'.
  561. if (!in_string_name && in_region == -1 && str[j] == '&' && !is_binary_op) {
  562. if (j + 1 <= line_length - 1 && (str[j + 1] == '\'' || str[j + 1] == '"')) {
  563. in_string_name = true;
  564. // Cover edge cases of i.e. '+&""' and '&&&""', so the StringName is properly colored.
  565. if (prev_is_binary_op && j >= 2 && str[j - 1] == '&' && str[j - 2] != '&') {
  566. in_string_name = false;
  567. is_binary_op = true;
  568. }
  569. } else {
  570. is_binary_op = true;
  571. }
  572. } else if (in_region != -1 || is_a_symbol) {
  573. in_string_name = false;
  574. }
  575. // '^^' has no special meaning, so unlike StringName, when binary, use NodePath color for the last caret.
  576. if (!in_node_path && in_region == -1 && str[j] == '^' && !is_binary_op && (j == 0 || (j > 0 && str[j - 1] != '^') || prev_is_binary_op)) {
  577. in_node_path = true;
  578. } else if (in_region != -1 || is_a_symbol) {
  579. in_node_path = false;
  580. }
  581. if (!in_node_ref && in_region == -1 && (str[j] == '$' || (str[j] == '%' && !is_binary_op))) {
  582. in_node_ref = true;
  583. } else if (in_region != -1 || (is_a_symbol && str[j] != '/' && str[j] != '%') || (is_a_digit && j > 0 && (str[j - 1] == '$' || str[j - 1] == '/' || str[j - 1] == '%'))) {
  584. // NodeRefs can't start with digits, so point out wrong syntax immediately.
  585. in_node_ref = false;
  586. }
  587. if (!in_annotation && in_region == -1 && str[j] == '@') {
  588. in_annotation = true;
  589. } else if (in_region != -1 || is_a_symbol) {
  590. in_annotation = false;
  591. }
  592. const bool in_raw_string_prefix = in_region == -1 && str[j] == 'r' && j + 1 < line_length && (str[j + 1] == '"' || str[j + 1] == '\'');
  593. if (in_raw_string_prefix) {
  594. color = string_color;
  595. } else if (in_node_ref) {
  596. next_type = NODE_REF;
  597. color = node_ref_color;
  598. } else if (in_annotation) {
  599. next_type = ANNOTATION;
  600. color = annotation_color;
  601. } else if (in_string_name) {
  602. next_type = STRING_NAME;
  603. color = string_name_color;
  604. } else if (in_node_path) {
  605. next_type = NODE_PATH;
  606. color = node_path_color;
  607. } else if (in_keyword) {
  608. next_type = KEYWORD;
  609. color = keyword_color;
  610. } else if (in_signal_declaration) {
  611. next_type = SIGNAL;
  612. color = member_variable_color;
  613. } else if (in_function_name) {
  614. next_type = FUNCTION;
  615. if (!in_lambda && in_function_declaration) {
  616. color = function_definition_color;
  617. } else {
  618. color = function_color;
  619. }
  620. } else if (in_number) {
  621. next_type = NUMBER;
  622. color = number_color;
  623. } else if (is_a_symbol) {
  624. next_type = SYMBOL;
  625. color = symbol_color;
  626. } else if (expect_type) {
  627. next_type = TYPE;
  628. color = type_color;
  629. } else if (in_member_variable) {
  630. next_type = MEMBER;
  631. color = member_variable_color;
  632. } else {
  633. next_type = IDENTIFIER;
  634. }
  635. if (next_type != current_type) {
  636. if (current_type == NONE) {
  637. current_type = next_type;
  638. } else {
  639. prev_type = current_type;
  640. current_type = next_type;
  641. // No need to store regions...
  642. if (prev_type == REGION) {
  643. prev_text = "";
  644. prev_column = j;
  645. } else {
  646. String text = str.substr(prev_column, j - prev_column).strip_edges();
  647. prev_column = j;
  648. // Ignore if just whitespace.
  649. if (!text.is_empty()) {
  650. prev_text = text;
  651. }
  652. }
  653. }
  654. }
  655. prev_is_char = is_char;
  656. prev_is_digit = is_a_digit;
  657. prev_is_binary_op = is_binary_op;
  658. if (color != prev_color) {
  659. prev_color = color;
  660. highlighter_info["color"] = color;
  661. color_map[j] = highlighter_info;
  662. }
  663. }
  664. return color_map;
  665. }
  666. String GDScriptSyntaxHighlighter::_get_name() const {
  667. return "GDScript";
  668. }
  669. PackedStringArray GDScriptSyntaxHighlighter::_get_supported_languages() const {
  670. PackedStringArray languages;
  671. languages.push_back("GDScript");
  672. return languages;
  673. }
  674. void GDScriptSyntaxHighlighter::_update_cache() {
  675. class_names.clear();
  676. reserved_keywords.clear();
  677. member_keywords.clear();
  678. global_functions.clear();
  679. color_regions.clear();
  680. color_region_cache.clear();
  681. font_color = text_edit->get_theme_color(SceneStringName(font_color));
  682. symbol_color = EDITOR_GET("text_editor/theme/highlighting/symbol_color");
  683. function_color = EDITOR_GET("text_editor/theme/highlighting/function_color");
  684. number_color = EDITOR_GET("text_editor/theme/highlighting/number_color");
  685. member_variable_color = EDITOR_GET("text_editor/theme/highlighting/member_variable_color");
  686. /* Engine types. */
  687. const Color types_color = EDITOR_GET("text_editor/theme/highlighting/engine_type_color");
  688. LocalVector<StringName> types;
  689. ClassDB::get_class_list(types);
  690. for (const StringName &type : types) {
  691. if (ClassDB::is_class_exposed(type)) {
  692. class_names[type] = types_color;
  693. }
  694. }
  695. /* Global enums. */
  696. List<StringName> global_enums;
  697. CoreConstants::get_global_enums(&global_enums);
  698. for (const StringName &enum_name : global_enums) {
  699. class_names[enum_name] = types_color;
  700. }
  701. /* User types. */
  702. const Color usertype_color = EDITOR_GET("text_editor/theme/highlighting/user_type_color");
  703. LocalVector<StringName> global_classes;
  704. ScriptServer::get_global_class_list(global_classes);
  705. for (const StringName &class_name : global_classes) {
  706. class_names[class_name] = usertype_color;
  707. }
  708. /* Autoloads. */
  709. for (const KeyValue<StringName, ProjectSettings::AutoloadInfo> &E : ProjectSettings::get_singleton()->get_autoload_list()) {
  710. const ProjectSettings::AutoloadInfo &info = E.value;
  711. if (info.is_singleton) {
  712. class_names[info.name] = usertype_color;
  713. }
  714. }
  715. const GDScriptLanguage *gdscript = GDScriptLanguage::get_singleton();
  716. /* Core types. */
  717. const Color basetype_color = EDITOR_GET("text_editor/theme/highlighting/base_type_color");
  718. List<String> core_types;
  719. gdscript->get_core_type_words(&core_types);
  720. for (const String &E : core_types) {
  721. class_names[StringName(E)] = basetype_color;
  722. }
  723. class_names[SNAME("Variant")] = basetype_color;
  724. class_names[SNAME("void")] = basetype_color;
  725. // `get_core_type_words()` doesn't return primitive types.
  726. class_names[SNAME("bool")] = basetype_color;
  727. class_names[SNAME("int")] = basetype_color;
  728. class_names[SNAME("float")] = basetype_color;
  729. /* Reserved words. */
  730. const Color keyword_color = EDITOR_GET("text_editor/theme/highlighting/keyword_color");
  731. const Color control_flow_keyword_color = EDITOR_GET("text_editor/theme/highlighting/control_flow_keyword_color");
  732. for (const String &keyword : gdscript->get_reserved_words()) {
  733. if (gdscript->is_control_flow_keyword(keyword)) {
  734. reserved_keywords[StringName(keyword)] = control_flow_keyword_color;
  735. } else {
  736. reserved_keywords[StringName(keyword)] = keyword_color;
  737. }
  738. }
  739. // Highlight `set` and `get` as "keywords" with the function color to avoid conflicts with method calls.
  740. reserved_keywords[SNAME("set")] = function_color;
  741. reserved_keywords[SNAME("get")] = function_color;
  742. /* Global functions. */
  743. List<StringName> global_function_list;
  744. GDScriptUtilityFunctions::get_function_list(&global_function_list);
  745. Variant::get_utility_function_list(&global_function_list);
  746. // "assert" and "preload" are not utility functions, but are global nonetheless, so insert them.
  747. global_functions.insert(SNAME("assert"));
  748. global_functions.insert(SNAME("preload"));
  749. for (const StringName &E : global_function_list) {
  750. global_functions.insert(E);
  751. }
  752. /* Comments. */
  753. const Color comment_color = EDITOR_GET("text_editor/theme/highlighting/comment_color");
  754. for (const String &comment : gdscript->get_comment_delimiters()) {
  755. String beg = comment.get_slicec(' ', 0);
  756. String end = comment.get_slice_count(" ") > 1 ? comment.get_slicec(' ', 1) : String();
  757. add_color_region(ColorRegion::TYPE_COMMENT, beg, end, comment_color, end.is_empty());
  758. }
  759. /* Doc comments */
  760. const Color doc_comment_color = EDITOR_GET("text_editor/theme/highlighting/doc_comment_color");
  761. for (const String &doc_comment : gdscript->get_doc_comment_delimiters()) {
  762. String beg = doc_comment.get_slicec(' ', 0);
  763. String end = doc_comment.get_slice_count(" ") > 1 ? doc_comment.get_slicec(' ', 1) : String();
  764. add_color_region(ColorRegion::TYPE_COMMENT, beg, end, doc_comment_color, end.is_empty());
  765. }
  766. /* Code regions */
  767. const Color code_region_color = Color(EDITOR_GET("text_editor/theme/highlighting/folded_code_region_color").operator Color(), 1.0);
  768. add_color_region(ColorRegion::TYPE_CODE_REGION, "#region", "", code_region_color, true);
  769. add_color_region(ColorRegion::TYPE_CODE_REGION, "#endregion", "", code_region_color, true);
  770. /* Strings */
  771. string_color = EDITOR_GET("text_editor/theme/highlighting/string_color");
  772. placeholder_color = EDITOR_GET("text_editor/theme/highlighting/string_placeholder_color");
  773. add_color_region(ColorRegion::TYPE_STRING, "\"", "\"", string_color);
  774. add_color_region(ColorRegion::TYPE_STRING, "'", "'", string_color);
  775. add_color_region(ColorRegion::TYPE_MULTILINE_STRING, "\"\"\"", "\"\"\"", string_color);
  776. add_color_region(ColorRegion::TYPE_MULTILINE_STRING, "'''", "'''", string_color);
  777. add_color_region(ColorRegion::TYPE_STRING, "\"", "\"", string_color, false, true);
  778. add_color_region(ColorRegion::TYPE_STRING, "'", "'", string_color, false, true);
  779. add_color_region(ColorRegion::TYPE_MULTILINE_STRING, "\"\"\"", "\"\"\"", string_color, false, true);
  780. add_color_region(ColorRegion::TYPE_MULTILINE_STRING, "'''", "'''", string_color, false, true);
  781. /* Members. */
  782. Ref<Script> scr = _get_edited_resource();
  783. if (scr.is_valid()) {
  784. StringName instance_base = scr->get_instance_base_type();
  785. if (instance_base != StringName()) {
  786. List<PropertyInfo> property_list;
  787. ClassDB::get_property_list(instance_base, &property_list);
  788. for (const PropertyInfo &E : property_list) {
  789. String prop_name = E.name;
  790. if (E.usage & PROPERTY_USAGE_CATEGORY || E.usage & PROPERTY_USAGE_GROUP || E.usage & PROPERTY_USAGE_SUBGROUP) {
  791. continue;
  792. }
  793. if (prop_name.contains_char('/')) {
  794. continue;
  795. }
  796. member_keywords[prop_name] = member_variable_color;
  797. }
  798. List<MethodInfo> signal_list;
  799. ClassDB::get_signal_list(instance_base, &signal_list);
  800. for (const MethodInfo &E : signal_list) {
  801. member_keywords[E.name] = member_variable_color;
  802. }
  803. // For callables.
  804. List<MethodInfo> method_list;
  805. ClassDB::get_method_list(instance_base, &method_list);
  806. for (const MethodInfo &E : method_list) {
  807. member_keywords[E.name] = member_variable_color;
  808. }
  809. List<String> constant_list;
  810. ClassDB::get_integer_constant_list(instance_base, &constant_list);
  811. for (const String &E : constant_list) {
  812. member_keywords[E] = member_variable_color;
  813. }
  814. List<StringName> builtin_enums;
  815. ClassDB::get_enum_list(instance_base, &builtin_enums);
  816. for (const StringName &E : builtin_enums) {
  817. member_keywords[E] = types_color;
  818. }
  819. }
  820. List<PropertyInfo> scr_property_list;
  821. scr->get_script_property_list(&scr_property_list);
  822. for (const PropertyInfo &E : scr_property_list) {
  823. String prop_name = E.name;
  824. if (E.usage & PROPERTY_USAGE_CATEGORY || E.usage & PROPERTY_USAGE_GROUP || E.usage & PROPERTY_USAGE_SUBGROUP) {
  825. continue;
  826. }
  827. if (prop_name.contains_char('/')) {
  828. continue;
  829. }
  830. member_keywords[prop_name] = member_variable_color;
  831. }
  832. List<MethodInfo> scr_signal_list;
  833. scr->get_script_signal_list(&scr_signal_list);
  834. for (const MethodInfo &E : scr_signal_list) {
  835. member_keywords[E.name] = member_variable_color;
  836. }
  837. // For callables.
  838. List<MethodInfo> scr_method_list;
  839. scr->get_script_method_list(&scr_method_list);
  840. for (const MethodInfo &E : scr_method_list) {
  841. member_keywords[E.name] = member_variable_color;
  842. }
  843. Ref<Script> scr_class = scr;
  844. while (scr_class.is_valid()) {
  845. HashMap<StringName, Variant> scr_constant_list;
  846. scr_class->get_constants(&scr_constant_list);
  847. for (const KeyValue<StringName, Variant> &E : scr_constant_list) {
  848. member_keywords[E.key.operator String()] = member_variable_color;
  849. }
  850. scr_class = scr_class->get_base_script();
  851. }
  852. }
  853. function_definition_color = EDITOR_GET("text_editor/theme/highlighting/gdscript/function_definition_color");
  854. global_function_color = EDITOR_GET("text_editor/theme/highlighting/gdscript/global_function_color");
  855. node_path_color = EDITOR_GET("text_editor/theme/highlighting/gdscript/node_path_color");
  856. node_ref_color = EDITOR_GET("text_editor/theme/highlighting/gdscript/node_reference_color");
  857. annotation_color = EDITOR_GET("text_editor/theme/highlighting/gdscript/annotation_color");
  858. string_name_color = EDITOR_GET("text_editor/theme/highlighting/gdscript/string_name_color");
  859. type_color = EDITOR_GET("text_editor/theme/highlighting/base_type_color");
  860. comment_marker_colors[COMMENT_MARKER_CRITICAL] = EDITOR_GET("text_editor/theme/highlighting/comment_markers/critical_color");
  861. comment_marker_colors[COMMENT_MARKER_WARNING] = EDITOR_GET("text_editor/theme/highlighting/comment_markers/warning_color");
  862. comment_marker_colors[COMMENT_MARKER_NOTICE] = EDITOR_GET("text_editor/theme/highlighting/comment_markers/notice_color");
  863. comment_markers.clear();
  864. Vector<String> critical_list = EDITOR_GET("text_editor/theme/highlighting/comment_markers/critical_list").operator String().split(",", false);
  865. for (int i = 0; i < critical_list.size(); i++) {
  866. comment_markers[critical_list[i]] = COMMENT_MARKER_CRITICAL;
  867. }
  868. Vector<String> warning_list = EDITOR_GET("text_editor/theme/highlighting/comment_markers/warning_list").operator String().split(",", false);
  869. for (int i = 0; i < warning_list.size(); i++) {
  870. comment_markers[warning_list[i]] = COMMENT_MARKER_WARNING;
  871. }
  872. Vector<String> notice_list = EDITOR_GET("text_editor/theme/highlighting/comment_markers/notice_list").operator String().split(",", false);
  873. for (int i = 0; i < notice_list.size(); i++) {
  874. comment_markers[notice_list[i]] = COMMENT_MARKER_NOTICE;
  875. }
  876. }
  877. void GDScriptSyntaxHighlighter::add_color_region(ColorRegion::Type p_type, const String &p_start_key, const String &p_end_key, const Color &p_color, bool p_line_only, bool p_r_prefix) {
  878. ERR_FAIL_COND_MSG(p_start_key.is_empty(), "Color region start key cannot be empty.");
  879. ERR_FAIL_COND_MSG(!is_symbol(p_start_key[0]), "Color region start key must start with a symbol.");
  880. if (!p_end_key.is_empty()) {
  881. ERR_FAIL_COND_MSG(!is_symbol(p_end_key[0]), "Color region end key must start with a symbol.");
  882. }
  883. int at = 0;
  884. for (const ColorRegion &region : color_regions) {
  885. ERR_FAIL_COND_MSG(region.start_key == p_start_key && region.r_prefix == p_r_prefix, "Color region with start key '" + p_start_key + "' already exists.");
  886. if (p_start_key.length() < region.start_key.length()) {
  887. at++;
  888. } else {
  889. break;
  890. }
  891. }
  892. ColorRegion color_region;
  893. color_region.type = p_type;
  894. color_region.color = p_color;
  895. color_region.start_key = p_start_key;
  896. color_region.end_key = p_end_key;
  897. color_region.line_only = p_line_only;
  898. color_region.r_prefix = p_r_prefix;
  899. color_region.is_string = p_type == ColorRegion::TYPE_STRING || p_type == ColorRegion::TYPE_MULTILINE_STRING;
  900. color_region.is_comment = p_type == ColorRegion::TYPE_COMMENT || p_type == ColorRegion::TYPE_CODE_REGION;
  901. color_regions.insert(at, color_region);
  902. clear_highlighting_cache();
  903. }
  904. Ref<EditorSyntaxHighlighter> GDScriptSyntaxHighlighter::_create() const {
  905. Ref<GDScriptSyntaxHighlighter> syntax_highlighter;
  906. syntax_highlighter.instantiate();
  907. return syntax_highlighter;
  908. }