gdscript_tokenizer.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658
  1. /**************************************************************************/
  2. /* gdscript_tokenizer.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_tokenizer.h"
  31. #include "core/error/error_macros.h"
  32. #include "core/string/char_utils.h"
  33. #ifdef DEBUG_ENABLED
  34. #include "servers/text_server.h"
  35. #endif
  36. #ifdef TOOLS_ENABLED
  37. #include "editor/editor_settings.h"
  38. #endif
  39. static const char *token_names[] = {
  40. "Empty", // EMPTY,
  41. // Basic
  42. "Annotation", // ANNOTATION
  43. "Identifier", // IDENTIFIER,
  44. "Literal", // LITERAL,
  45. // Comparison
  46. "<", // LESS,
  47. "<=", // LESS_EQUAL,
  48. ">", // GREATER,
  49. ">=", // GREATER_EQUAL,
  50. "==", // EQUAL_EQUAL,
  51. "!=", // BANG_EQUAL,
  52. // Logical
  53. "and", // AND,
  54. "or", // OR,
  55. "not", // NOT,
  56. "&&", // AMPERSAND_AMPERSAND,
  57. "||", // PIPE_PIPE,
  58. "!", // BANG,
  59. // Bitwise
  60. "&", // AMPERSAND,
  61. "|", // PIPE,
  62. "~", // TILDE,
  63. "^", // CARET,
  64. "<<", // LESS_LESS,
  65. ">>", // GREATER_GREATER,
  66. // Math
  67. "+", // PLUS,
  68. "-", // MINUS,
  69. "*", // STAR,
  70. "**", // STAR_STAR,
  71. "/", // SLASH,
  72. "%", // PERCENT,
  73. // Assignment
  74. "=", // EQUAL,
  75. "+=", // PLUS_EQUAL,
  76. "-=", // MINUS_EQUAL,
  77. "*=", // STAR_EQUAL,
  78. "**=", // STAR_STAR_EQUAL,
  79. "/=", // SLASH_EQUAL,
  80. "%=", // PERCENT_EQUAL,
  81. "<<=", // LESS_LESS_EQUAL,
  82. ">>=", // GREATER_GREATER_EQUAL,
  83. "&=", // AMPERSAND_EQUAL,
  84. "|=", // PIPE_EQUAL,
  85. "^=", // CARET_EQUAL,
  86. // Control flow
  87. "if", // IF,
  88. "elif", // ELIF,
  89. "else", // ELSE,
  90. "for", // FOR,
  91. "while", // WHILE,
  92. "break", // BREAK,
  93. "continue", // CONTINUE,
  94. "pass", // PASS,
  95. "return", // RETURN,
  96. "match", // MATCH,
  97. "when", // WHEN,
  98. // Keywords
  99. "abstract", // ABSTRACT,
  100. "as", // AS,
  101. "assert", // ASSERT,
  102. "await", // AWAIT,
  103. "breakpoint", // BREAKPOINT,
  104. "class", // CLASS,
  105. "class_name", // CLASS_NAME,
  106. "const", // TK_CONST,
  107. "enum", // ENUM,
  108. "extends", // EXTENDS,
  109. "func", // FUNC,
  110. "in", // TK_IN,
  111. "is", // IS,
  112. "namespace", // NAMESPACE
  113. "preload", // PRELOAD,
  114. "self", // SELF,
  115. "signal", // SIGNAL,
  116. "static", // STATIC,
  117. "super", // SUPER,
  118. "trait", // TRAIT,
  119. "var", // VAR,
  120. "void", // TK_VOID,
  121. "yield", // YIELD,
  122. // Punctuation
  123. "[", // BRACKET_OPEN,
  124. "]", // BRACKET_CLOSE,
  125. "{", // BRACE_OPEN,
  126. "}", // BRACE_CLOSE,
  127. "(", // PARENTHESIS_OPEN,
  128. ")", // PARENTHESIS_CLOSE,
  129. ",", // COMMA,
  130. ";", // SEMICOLON,
  131. ".", // PERIOD,
  132. "..", // PERIOD_PERIOD,
  133. "...", // PERIOD_PERIOD_PERIOD,
  134. ":", // COLON,
  135. "$", // DOLLAR,
  136. "->", // FORWARD_ARROW,
  137. "_", // UNDERSCORE,
  138. // Whitespace
  139. "Newline", // NEWLINE,
  140. "Indent", // INDENT,
  141. "Dedent", // DEDENT,
  142. // Constants
  143. "PI", // CONST_PI,
  144. "TAU", // CONST_TAU,
  145. "INF", // CONST_INF,
  146. "NaN", // CONST_NAN,
  147. // Error message improvement
  148. "VCS conflict marker", // VCS_CONFLICT_MARKER,
  149. "`", // BACKTICK,
  150. "?", // QUESTION_MARK,
  151. // Special
  152. "Error", // ERROR,
  153. "End of file", // EOF,
  154. };
  155. // Avoid desync.
  156. static_assert(std::size(token_names) == GDScriptTokenizer::Token::TK_MAX, "Amount of token names don't match the amount of token types.");
  157. const char *GDScriptTokenizer::Token::get_name() const {
  158. ERR_FAIL_INDEX_V_MSG(type, TK_MAX, "<error>", "Using token type out of the enum.");
  159. return token_names[type];
  160. }
  161. String GDScriptTokenizer::Token::get_debug_name() const {
  162. switch (type) {
  163. case IDENTIFIER:
  164. return vformat(R"(identifier "%s")", source);
  165. default:
  166. return vformat(R"("%s")", get_name());
  167. }
  168. }
  169. bool GDScriptTokenizer::Token::can_precede_bin_op() const {
  170. switch (type) {
  171. case IDENTIFIER:
  172. case LITERAL:
  173. case SELF:
  174. case BRACKET_CLOSE:
  175. case BRACE_CLOSE:
  176. case PARENTHESIS_CLOSE:
  177. case CONST_PI:
  178. case CONST_TAU:
  179. case CONST_INF:
  180. case CONST_NAN:
  181. return true;
  182. default:
  183. return false;
  184. }
  185. }
  186. bool GDScriptTokenizer::Token::is_identifier() const {
  187. // Note: Most keywords should not be recognized as identifiers.
  188. // These are only exceptions for stuff that already is on the engine's API.
  189. switch (type) {
  190. case IDENTIFIER:
  191. case MATCH: // Used in String.match().
  192. case WHEN: // New keyword, avoid breaking existing code.
  193. case ABSTRACT:
  194. // Allow constants to be treated as regular identifiers.
  195. case CONST_PI:
  196. case CONST_INF:
  197. case CONST_NAN:
  198. case CONST_TAU:
  199. return true;
  200. default:
  201. return false;
  202. }
  203. }
  204. bool GDScriptTokenizer::Token::is_node_name() const {
  205. // This is meant to allow keywords with the $ notation, but not as general identifiers.
  206. switch (type) {
  207. case IDENTIFIER:
  208. case ABSTRACT:
  209. case AND:
  210. case AS:
  211. case ASSERT:
  212. case AWAIT:
  213. case BREAK:
  214. case BREAKPOINT:
  215. case CLASS_NAME:
  216. case CLASS:
  217. case TK_CONST:
  218. case CONST_PI:
  219. case CONST_INF:
  220. case CONST_NAN:
  221. case CONST_TAU:
  222. case CONTINUE:
  223. case ELIF:
  224. case ELSE:
  225. case ENUM:
  226. case EXTENDS:
  227. case FOR:
  228. case FUNC:
  229. case IF:
  230. case TK_IN:
  231. case IS:
  232. case MATCH:
  233. case NAMESPACE:
  234. case NOT:
  235. case OR:
  236. case PASS:
  237. case PRELOAD:
  238. case RETURN:
  239. case SELF:
  240. case SIGNAL:
  241. case STATIC:
  242. case SUPER:
  243. case TRAIT:
  244. case UNDERSCORE:
  245. case VAR:
  246. case TK_VOID:
  247. case WHILE:
  248. case WHEN:
  249. case YIELD:
  250. return true;
  251. default:
  252. return false;
  253. }
  254. }
  255. String GDScriptTokenizer::get_token_name(Token::Type p_token_type) {
  256. ERR_FAIL_INDEX_V_MSG(p_token_type, Token::TK_MAX, "<error>", "Using token type out of the enum.");
  257. return token_names[p_token_type];
  258. }
  259. void GDScriptTokenizerText::set_source_code(const String &p_source_code) {
  260. source = p_source_code;
  261. if (source.is_empty()) {
  262. _source = U"";
  263. } else {
  264. _source = source.ptr();
  265. }
  266. _current = _source;
  267. line = 1;
  268. column = 1;
  269. length = p_source_code.length();
  270. position = 0;
  271. }
  272. void GDScriptTokenizerText::set_cursor_position(int p_line, int p_column) {
  273. cursor_line = p_line;
  274. cursor_column = p_column;
  275. }
  276. void GDScriptTokenizerText::set_multiline_mode(bool p_state) {
  277. multiline_mode = p_state;
  278. }
  279. void GDScriptTokenizerText::push_expression_indented_block() {
  280. indent_stack_stack.push_back(indent_stack);
  281. }
  282. void GDScriptTokenizerText::pop_expression_indented_block() {
  283. ERR_FAIL_COND(indent_stack_stack.is_empty());
  284. indent_stack = indent_stack_stack.back()->get();
  285. indent_stack_stack.pop_back();
  286. }
  287. int GDScriptTokenizerText::get_cursor_line() const {
  288. return cursor_line;
  289. }
  290. int GDScriptTokenizerText::get_cursor_column() const {
  291. return cursor_column;
  292. }
  293. bool GDScriptTokenizerText::is_past_cursor() const {
  294. if (line < cursor_line) {
  295. return false;
  296. }
  297. if (line > cursor_line) {
  298. return true;
  299. }
  300. if (column < cursor_column) {
  301. return false;
  302. }
  303. return true;
  304. }
  305. char32_t GDScriptTokenizerText::_advance() {
  306. if (unlikely(_is_at_end())) {
  307. return '\0';
  308. }
  309. _current++;
  310. column++;
  311. position++;
  312. if (unlikely(_is_at_end())) {
  313. // Add extra newline even if it's not there, to satisfy the parser.
  314. newline(true);
  315. // Also add needed unindent.
  316. check_indent();
  317. }
  318. return _peek(-1);
  319. }
  320. void GDScriptTokenizerText::push_paren(char32_t p_char) {
  321. paren_stack.push_back(p_char);
  322. }
  323. bool GDScriptTokenizerText::pop_paren(char32_t p_expected) {
  324. if (paren_stack.is_empty()) {
  325. return false;
  326. }
  327. char32_t actual = paren_stack.back()->get();
  328. paren_stack.pop_back();
  329. return actual == p_expected;
  330. }
  331. GDScriptTokenizer::Token GDScriptTokenizerText::pop_error() {
  332. Token error = error_stack.back()->get();
  333. error_stack.pop_back();
  334. return error;
  335. }
  336. GDScriptTokenizer::Token GDScriptTokenizerText::make_token(Token::Type p_type) {
  337. Token token(p_type);
  338. token.start_line = start_line;
  339. token.end_line = line;
  340. token.start_column = start_column;
  341. token.end_column = column;
  342. token.source = String::utf32(Span(_start, _current - _start));
  343. if (p_type != Token::ERROR && cursor_line > -1) {
  344. // Also count whitespace after token.
  345. int offset = 0;
  346. while (_peek(offset) == ' ' || _peek(offset) == '\t') {
  347. offset++;
  348. }
  349. int last_column = column + offset;
  350. // Check cursor position in token.
  351. if (start_line == line) {
  352. // Single line token.
  353. if (cursor_line == start_line && cursor_column >= start_column && cursor_column <= last_column) {
  354. token.cursor_position = cursor_column - start_column;
  355. if (cursor_column == start_column) {
  356. token.cursor_place = CURSOR_BEGINNING;
  357. } else if (cursor_column < column) {
  358. token.cursor_place = CURSOR_MIDDLE;
  359. } else {
  360. token.cursor_place = CURSOR_END;
  361. }
  362. }
  363. } else {
  364. // Multi line token.
  365. if (cursor_line == start_line && cursor_column >= start_column) {
  366. // Is in first line.
  367. token.cursor_position = cursor_column - start_column;
  368. if (cursor_column == start_column) {
  369. token.cursor_place = CURSOR_BEGINNING;
  370. } else {
  371. token.cursor_place = CURSOR_MIDDLE;
  372. }
  373. } else if (cursor_line == line && cursor_column <= last_column) {
  374. // Is in last line.
  375. token.cursor_position = cursor_column - start_column;
  376. if (cursor_column < column) {
  377. token.cursor_place = CURSOR_MIDDLE;
  378. } else {
  379. token.cursor_place = CURSOR_END;
  380. }
  381. } else if (cursor_line > start_line && cursor_line < line) {
  382. // Is in middle line.
  383. token.cursor_position = CURSOR_MIDDLE;
  384. }
  385. }
  386. }
  387. last_token = token;
  388. return token;
  389. }
  390. GDScriptTokenizer::Token GDScriptTokenizerText::make_literal(const Variant &p_literal) {
  391. Token token = make_token(Token::LITERAL);
  392. token.literal = p_literal;
  393. return token;
  394. }
  395. GDScriptTokenizer::Token GDScriptTokenizerText::make_identifier(const StringName &p_identifier) {
  396. Token identifier = make_token(Token::IDENTIFIER);
  397. identifier.literal = p_identifier;
  398. return identifier;
  399. }
  400. GDScriptTokenizer::Token GDScriptTokenizerText::make_error(const String &p_message) {
  401. Token error = make_token(Token::ERROR);
  402. error.literal = p_message;
  403. return error;
  404. }
  405. void GDScriptTokenizerText::push_error(const String &p_message) {
  406. Token error = make_error(p_message);
  407. error_stack.push_back(error);
  408. }
  409. void GDScriptTokenizerText::push_error(const Token &p_error) {
  410. error_stack.push_back(p_error);
  411. }
  412. GDScriptTokenizer::Token GDScriptTokenizerText::make_paren_error(char32_t p_paren) {
  413. if (paren_stack.is_empty()) {
  414. return make_error(vformat("Closing \"%c\" doesn't have an opening counterpart.", p_paren));
  415. }
  416. Token error = make_error(vformat("Closing \"%c\" doesn't match the opening \"%c\".", p_paren, paren_stack.back()->get()));
  417. paren_stack.pop_back(); // Remove opening one anyway.
  418. return error;
  419. }
  420. GDScriptTokenizer::Token GDScriptTokenizerText::check_vcs_marker(char32_t p_test, Token::Type p_double_type) {
  421. const char32_t *next = _current + 1;
  422. int chars = 2; // Two already matched.
  423. // Test before consuming characters, since we don't want to consume more than needed.
  424. while (*next == p_test) {
  425. chars++;
  426. next++;
  427. }
  428. if (chars >= 7) {
  429. // It is a VCS conflict marker.
  430. while (chars > 1) {
  431. // Consume all characters (first was already consumed by scan()).
  432. _advance();
  433. chars--;
  434. }
  435. return make_token(Token::VCS_CONFLICT_MARKER);
  436. } else {
  437. // It is only a regular double character token, so we consume the second character.
  438. _advance();
  439. return make_token(p_double_type);
  440. }
  441. }
  442. GDScriptTokenizer::Token GDScriptTokenizerText::annotation() {
  443. if (is_unicode_identifier_start(_peek())) {
  444. _advance(); // Consume start character.
  445. } else {
  446. push_error("Expected annotation identifier after \"@\".");
  447. }
  448. while (is_unicode_identifier_continue(_peek())) {
  449. // Consume all identifier characters.
  450. _advance();
  451. }
  452. Token annotation = make_token(Token::ANNOTATION);
  453. annotation.literal = StringName(annotation.source);
  454. return annotation;
  455. }
  456. #define KEYWORDS(KEYWORD_GROUP, KEYWORD) \
  457. KEYWORD_GROUP('a') \
  458. KEYWORD("abstract", Token::ABSTRACT) \
  459. KEYWORD("as", Token::AS) \
  460. KEYWORD("and", Token::AND) \
  461. KEYWORD("assert", Token::ASSERT) \
  462. KEYWORD("await", Token::AWAIT) \
  463. KEYWORD_GROUP('b') \
  464. KEYWORD("break", Token::BREAK) \
  465. KEYWORD("breakpoint", Token::BREAKPOINT) \
  466. KEYWORD_GROUP('c') \
  467. KEYWORD("class", Token::CLASS) \
  468. KEYWORD("class_name", Token::CLASS_NAME) \
  469. KEYWORD("const", Token::TK_CONST) \
  470. KEYWORD("continue", Token::CONTINUE) \
  471. KEYWORD_GROUP('e') \
  472. KEYWORD("elif", Token::ELIF) \
  473. KEYWORD("else", Token::ELSE) \
  474. KEYWORD("enum", Token::ENUM) \
  475. KEYWORD("extends", Token::EXTENDS) \
  476. KEYWORD_GROUP('f') \
  477. KEYWORD("for", Token::FOR) \
  478. KEYWORD("func", Token::FUNC) \
  479. KEYWORD_GROUP('i') \
  480. KEYWORD("if", Token::IF) \
  481. KEYWORD("in", Token::TK_IN) \
  482. KEYWORD("is", Token::IS) \
  483. KEYWORD_GROUP('m') \
  484. KEYWORD("match", Token::MATCH) \
  485. KEYWORD_GROUP('n') \
  486. KEYWORD("namespace", Token::NAMESPACE) \
  487. KEYWORD("not", Token::NOT) \
  488. KEYWORD_GROUP('o') \
  489. KEYWORD("or", Token::OR) \
  490. KEYWORD_GROUP('p') \
  491. KEYWORD("pass", Token::PASS) \
  492. KEYWORD("preload", Token::PRELOAD) \
  493. KEYWORD_GROUP('r') \
  494. KEYWORD("return", Token::RETURN) \
  495. KEYWORD_GROUP('s') \
  496. KEYWORD("self", Token::SELF) \
  497. KEYWORD("signal", Token::SIGNAL) \
  498. KEYWORD("static", Token::STATIC) \
  499. KEYWORD("super", Token::SUPER) \
  500. KEYWORD_GROUP('t') \
  501. KEYWORD("trait", Token::TRAIT) \
  502. KEYWORD_GROUP('v') \
  503. KEYWORD("var", Token::VAR) \
  504. KEYWORD("void", Token::TK_VOID) \
  505. KEYWORD_GROUP('w') \
  506. KEYWORD("while", Token::WHILE) \
  507. KEYWORD("when", Token::WHEN) \
  508. KEYWORD_GROUP('y') \
  509. KEYWORD("yield", Token::YIELD) \
  510. KEYWORD_GROUP('I') \
  511. KEYWORD("INF", Token::CONST_INF) \
  512. KEYWORD_GROUP('N') \
  513. KEYWORD("NAN", Token::CONST_NAN) \
  514. KEYWORD_GROUP('P') \
  515. KEYWORD("PI", Token::CONST_PI) \
  516. KEYWORD_GROUP('T') \
  517. KEYWORD("TAU", Token::CONST_TAU)
  518. #define MIN_KEYWORD_LENGTH 2
  519. #define MAX_KEYWORD_LENGTH 10
  520. #ifdef DEBUG_ENABLED
  521. void GDScriptTokenizerText::make_keyword_list() {
  522. #define KEYWORD_LINE(keyword, token_type) keyword,
  523. #define KEYWORD_GROUP_IGNORE(group)
  524. keyword_list = {
  525. KEYWORDS(KEYWORD_GROUP_IGNORE, KEYWORD_LINE)
  526. };
  527. #undef KEYWORD_LINE
  528. #undef KEYWORD_GROUP_IGNORE
  529. }
  530. #endif // DEBUG_ENABLED
  531. GDScriptTokenizer::Token GDScriptTokenizerText::potential_identifier() {
  532. bool only_ascii = _peek(-1) < 128;
  533. // Consume all identifier characters.
  534. while (is_unicode_identifier_continue(_peek())) {
  535. char32_t c = _advance();
  536. only_ascii = only_ascii && c < 128;
  537. }
  538. int len = _current - _start;
  539. if (len == 1 && _peek(-1) == '_') {
  540. // Lone underscore.
  541. Token token = make_token(Token::UNDERSCORE);
  542. token.literal = "_";
  543. return token;
  544. }
  545. String name = String::utf32(Span(_start, len));
  546. if (len < MIN_KEYWORD_LENGTH || len > MAX_KEYWORD_LENGTH) {
  547. // Cannot be a keyword, as the length doesn't match any.
  548. return make_identifier(name);
  549. }
  550. if (!only_ascii) {
  551. // Kept here in case the order with push_error matters.
  552. Token id = make_identifier(name);
  553. #ifdef DEBUG_ENABLED
  554. // Additional checks for identifiers but only in debug and if it's available in TextServer.
  555. if (TS->has_feature(TextServer::FEATURE_UNICODE_SECURITY)) {
  556. int64_t confusable = TS->is_confusable(name, keyword_list);
  557. if (confusable >= 0) {
  558. push_error(vformat(R"(Identifier "%s" is visually similar to the GDScript keyword "%s" and thus not allowed.)", name, keyword_list[confusable]));
  559. }
  560. }
  561. #endif // DEBUG_ENABLED
  562. // Cannot be a keyword, as keywords are ASCII only.
  563. return id;
  564. }
  565. // Define some helper macros for the switch case.
  566. #define KEYWORD_GROUP_CASE(char) \
  567. break; \
  568. case char:
  569. #define KEYWORD(keyword, token_type) \
  570. { \
  571. const int keyword_length = sizeof(keyword) - 1; \
  572. static_assert(keyword_length <= MAX_KEYWORD_LENGTH, "There's a keyword longer than the defined maximum length"); \
  573. static_assert(keyword_length >= MIN_KEYWORD_LENGTH, "There's a keyword shorter than the defined minimum length"); \
  574. if (keyword_length == len && name == keyword) { \
  575. Token kw = make_token(token_type); \
  576. kw.literal = name; \
  577. return kw; \
  578. } \
  579. }
  580. // Find if it's a keyword.
  581. switch (_start[0]) {
  582. default:
  583. KEYWORDS(KEYWORD_GROUP_CASE, KEYWORD)
  584. break;
  585. }
  586. // Check if it's a special literal
  587. if (len == 4) {
  588. if (name == "true") {
  589. return make_literal(true);
  590. } else if (name == "null") {
  591. return make_literal(Variant());
  592. }
  593. } else if (len == 5) {
  594. if (name == "false") {
  595. return make_literal(false);
  596. }
  597. }
  598. // Not a keyword, so must be an identifier.
  599. return make_identifier(name);
  600. #undef KEYWORD_GROUP_CASE
  601. #undef KEYWORD
  602. }
  603. #undef MAX_KEYWORD_LENGTH
  604. #undef MIN_KEYWORD_LENGTH
  605. #undef KEYWORDS
  606. void GDScriptTokenizerText::newline(bool p_make_token) {
  607. // Don't overwrite previous newline, nor create if we want a line continuation.
  608. if (p_make_token && !pending_newline && !line_continuation) {
  609. Token newline(Token::NEWLINE);
  610. newline.start_line = line;
  611. newline.end_line = line;
  612. newline.start_column = column - 1;
  613. newline.end_column = column;
  614. pending_newline = true;
  615. last_token = newline;
  616. last_newline = newline;
  617. }
  618. // Increment line/column counters.
  619. line++;
  620. column = 1;
  621. }
  622. GDScriptTokenizer::Token GDScriptTokenizerText::number() {
  623. int base = 10;
  624. bool has_decimal = false;
  625. bool has_exponent = false;
  626. bool has_error = false;
  627. bool need_digits = false;
  628. bool (*digit_check_func)(char32_t) = is_digit;
  629. // Sign before hexadecimal or binary.
  630. if ((_peek(-1) == '+' || _peek(-1) == '-') && _peek() == '0') {
  631. _advance();
  632. }
  633. if (_peek(-1) == '.') {
  634. has_decimal = true;
  635. } else if (_peek(-1) == '0') {
  636. if (_peek() == 'x' || _peek() == 'X') {
  637. // Hexadecimal.
  638. base = 16;
  639. digit_check_func = is_hex_digit;
  640. need_digits = true;
  641. _advance();
  642. } else if (_peek() == 'b' || _peek() == 'B') {
  643. // Binary.
  644. base = 2;
  645. digit_check_func = is_binary_digit;
  646. need_digits = true;
  647. _advance();
  648. }
  649. }
  650. if (base != 10 && is_underscore(_peek())) { // Disallow `0x_` and `0b_`.
  651. Token error = make_error(vformat(R"(Unexpected underscore after "0%c".)", _peek(-1)));
  652. error.start_column = column;
  653. error.end_column = column + 1;
  654. push_error(error);
  655. has_error = true;
  656. }
  657. bool previous_was_underscore = false; // Allow `_` to be used in a number, for readability.
  658. while (digit_check_func(_peek()) || is_underscore(_peek())) {
  659. if (is_underscore(_peek())) {
  660. if (previous_was_underscore) {
  661. Token error = make_error(R"(Multiple underscores cannot be adjacent in a numeric literal.)");
  662. error.start_column = column;
  663. error.end_column = column + 1;
  664. push_error(error);
  665. }
  666. previous_was_underscore = true;
  667. } else {
  668. need_digits = false;
  669. previous_was_underscore = false;
  670. }
  671. _advance();
  672. }
  673. // It might be a ".." token (instead of decimal point) so we check if it's not.
  674. if (_peek() == '.' && _peek(1) != '.') {
  675. if (base == 10 && !has_decimal) {
  676. has_decimal = true;
  677. } else if (base == 10) {
  678. Token error = make_error("Cannot use a decimal point twice in a number.");
  679. error.start_column = column;
  680. error.end_column = column + 1;
  681. push_error(error);
  682. has_error = true;
  683. } else if (base == 16) {
  684. Token error = make_error("Cannot use a decimal point in a hexadecimal number.");
  685. error.start_column = column;
  686. error.end_column = column + 1;
  687. push_error(error);
  688. has_error = true;
  689. } else {
  690. Token error = make_error("Cannot use a decimal point in a binary number.");
  691. error.start_column = column;
  692. error.end_column = column + 1;
  693. push_error(error);
  694. has_error = true;
  695. }
  696. if (!has_error) {
  697. _advance();
  698. // Consume decimal digits.
  699. if (is_underscore(_peek())) { // Disallow `10._`, but allow `10.`.
  700. Token error = make_error(R"(Unexpected underscore after decimal point.)");
  701. error.start_column = column;
  702. error.end_column = column + 1;
  703. push_error(error);
  704. has_error = true;
  705. }
  706. previous_was_underscore = false;
  707. while (is_digit(_peek()) || is_underscore(_peek())) {
  708. if (is_underscore(_peek())) {
  709. if (previous_was_underscore) {
  710. Token error = make_error(R"(Multiple underscores cannot be adjacent in a numeric literal.)");
  711. error.start_column = column;
  712. error.end_column = column + 1;
  713. push_error(error);
  714. }
  715. previous_was_underscore = true;
  716. } else {
  717. previous_was_underscore = false;
  718. }
  719. _advance();
  720. }
  721. }
  722. }
  723. if (base == 10) {
  724. if (_peek() == 'e' || _peek() == 'E') {
  725. has_exponent = true;
  726. _advance();
  727. if (_peek() == '+' || _peek() == '-') {
  728. // Exponent sign.
  729. _advance();
  730. }
  731. // Consume exponent digits.
  732. if (!is_digit(_peek())) {
  733. Token error = make_error(R"(Expected exponent value after "e".)");
  734. error.start_column = column;
  735. error.end_column = column + 1;
  736. push_error(error);
  737. }
  738. previous_was_underscore = false;
  739. while (is_digit(_peek()) || is_underscore(_peek())) {
  740. if (is_underscore(_peek())) {
  741. if (previous_was_underscore) {
  742. Token error = make_error(R"(Multiple underscores cannot be adjacent in a numeric literal.)");
  743. error.start_column = column;
  744. error.end_column = column + 1;
  745. push_error(error);
  746. }
  747. previous_was_underscore = true;
  748. } else {
  749. previous_was_underscore = false;
  750. }
  751. _advance();
  752. }
  753. }
  754. }
  755. if (need_digits) {
  756. // No digits in hex or bin literal.
  757. Token error = make_error(vformat(R"(Expected %s digit after "0%c".)", (base == 16 ? "hexadecimal" : "binary"), (base == 16 ? 'x' : 'b')));
  758. error.start_column = column;
  759. error.end_column = column + 1;
  760. return error;
  761. }
  762. // Detect extra decimal point.
  763. if (!has_error && has_decimal && _peek() == '.' && _peek(1) != '.') {
  764. Token error = make_error("Cannot use a decimal point twice in a number.");
  765. error.start_column = column;
  766. error.end_column = column + 1;
  767. push_error(error);
  768. has_error = true;
  769. } else if (is_unicode_identifier_start(_peek()) || is_unicode_identifier_continue(_peek())) {
  770. // Letter at the end of the number.
  771. push_error("Invalid numeric notation.");
  772. }
  773. // Create a string with the whole number.
  774. int len = _current - _start;
  775. String number = String::utf32(Span(_start, len)).remove_char('_');
  776. // Convert to the appropriate literal type.
  777. if (base == 16) {
  778. int64_t value = number.hex_to_int();
  779. return make_literal(value);
  780. } else if (base == 2) {
  781. int64_t value = number.bin_to_int();
  782. return make_literal(value);
  783. } else if (has_decimal || has_exponent) {
  784. double value = number.to_float();
  785. return make_literal(value);
  786. } else {
  787. int64_t value = number.to_int();
  788. return make_literal(value);
  789. }
  790. }
  791. GDScriptTokenizer::Token GDScriptTokenizerText::string() {
  792. enum StringType {
  793. STRING_REGULAR,
  794. STRING_NAME,
  795. STRING_NODEPATH,
  796. };
  797. bool is_raw = false;
  798. bool is_multiline = false;
  799. StringType type = STRING_REGULAR;
  800. if (_peek(-1) == 'r') {
  801. is_raw = true;
  802. _advance();
  803. } else if (_peek(-1) == '&') {
  804. type = STRING_NAME;
  805. _advance();
  806. } else if (_peek(-1) == '^') {
  807. type = STRING_NODEPATH;
  808. _advance();
  809. }
  810. char32_t quote_char = _peek(-1);
  811. if (_peek() == quote_char && _peek(1) == quote_char) {
  812. is_multiline = true;
  813. // Consume all quotes.
  814. _advance();
  815. _advance();
  816. }
  817. String result;
  818. char32_t prev = 0;
  819. int prev_pos = 0;
  820. for (;;) {
  821. // Consume actual string.
  822. if (_is_at_end()) {
  823. return make_error("Unterminated string.");
  824. }
  825. char32_t ch = _peek();
  826. if (ch == 0x200E || ch == 0x200F || (ch >= 0x202A && ch <= 0x202E) || (ch >= 0x2066 && ch <= 0x2069)) {
  827. Token error;
  828. if (is_raw) {
  829. error = make_error("Invisible text direction control character present in the string, use regular string literal instead of r-string.");
  830. } else {
  831. error = make_error("Invisible text direction control character present in the string, escape it (\"\\u" + String::num_int64(ch, 16) + "\") to avoid confusion.");
  832. }
  833. error.start_column = column;
  834. error.end_column = column + 1;
  835. push_error(error);
  836. }
  837. if (ch == '\\') {
  838. // Escape pattern.
  839. _advance();
  840. if (_is_at_end()) {
  841. return make_error("Unterminated string.");
  842. }
  843. if (is_raw) {
  844. if (_peek() == quote_char) {
  845. _advance();
  846. if (_is_at_end()) {
  847. return make_error("Unterminated string.");
  848. }
  849. result += '\\';
  850. result += quote_char;
  851. } else if (_peek() == '\\') { // For `\\\"`.
  852. _advance();
  853. if (_is_at_end()) {
  854. return make_error("Unterminated string.");
  855. }
  856. result += '\\';
  857. result += '\\';
  858. } else {
  859. result += '\\';
  860. }
  861. } else {
  862. // Grab escape character.
  863. char32_t code = _peek();
  864. _advance();
  865. if (_is_at_end()) {
  866. return make_error("Unterminated string.");
  867. }
  868. char32_t escaped = 0;
  869. bool valid_escape = true;
  870. switch (code) {
  871. case 'a':
  872. escaped = '\a';
  873. break;
  874. case 'b':
  875. escaped = '\b';
  876. break;
  877. case 'f':
  878. escaped = '\f';
  879. break;
  880. case 'n':
  881. escaped = '\n';
  882. break;
  883. case 'r':
  884. escaped = '\r';
  885. break;
  886. case 't':
  887. escaped = '\t';
  888. break;
  889. case 'v':
  890. escaped = '\v';
  891. break;
  892. case '\'':
  893. escaped = '\'';
  894. break;
  895. case '\"':
  896. escaped = '\"';
  897. break;
  898. case '\\':
  899. escaped = '\\';
  900. break;
  901. case 'U':
  902. case 'u': {
  903. // Hexadecimal sequence.
  904. int hex_len = (code == 'U') ? 6 : 4;
  905. for (int j = 0; j < hex_len; j++) {
  906. if (_is_at_end()) {
  907. return make_error("Unterminated string.");
  908. }
  909. char32_t digit = _peek();
  910. char32_t value = 0;
  911. if (is_digit(digit)) {
  912. value = digit - '0';
  913. } else if (digit >= 'a' && digit <= 'f') {
  914. value = digit - 'a';
  915. value += 10;
  916. } else if (digit >= 'A' && digit <= 'F') {
  917. value = digit - 'A';
  918. value += 10;
  919. } else {
  920. // Make error, but keep parsing the string.
  921. Token error = make_error("Invalid hexadecimal digit in unicode escape sequence.");
  922. error.start_column = column;
  923. error.end_column = column + 1;
  924. push_error(error);
  925. valid_escape = false;
  926. break;
  927. }
  928. escaped <<= 4;
  929. escaped |= value;
  930. _advance();
  931. }
  932. } break;
  933. case '\r':
  934. if (_peek() != '\n') {
  935. // Carriage return without newline in string. (???)
  936. // Just add it to the string and keep going.
  937. result += ch;
  938. _advance();
  939. break;
  940. }
  941. [[fallthrough]];
  942. case '\n':
  943. // Escaping newline.
  944. newline(false);
  945. valid_escape = false; // Don't add to the string.
  946. break;
  947. default:
  948. Token error = make_error("Invalid escape in string.");
  949. error.start_column = column - 2;
  950. push_error(error);
  951. valid_escape = false;
  952. break;
  953. }
  954. // Parse UTF-16 pair.
  955. if (valid_escape) {
  956. if ((escaped & 0xfffffc00) == 0xd800) {
  957. if (prev == 0) {
  958. prev = escaped;
  959. prev_pos = column - 2;
  960. continue;
  961. } else {
  962. Token error = make_error("Invalid UTF-16 sequence in string, unpaired lead surrogate.");
  963. error.start_column = column - 2;
  964. push_error(error);
  965. valid_escape = false;
  966. prev = 0;
  967. }
  968. } else if ((escaped & 0xfffffc00) == 0xdc00) {
  969. if (prev == 0) {
  970. Token error = make_error("Invalid UTF-16 sequence in string, unpaired trail surrogate.");
  971. error.start_column = column - 2;
  972. push_error(error);
  973. valid_escape = false;
  974. } else {
  975. escaped = (prev << 10UL) + escaped - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
  976. prev = 0;
  977. }
  978. }
  979. if (prev != 0) {
  980. Token error = make_error("Invalid UTF-16 sequence in string, unpaired lead surrogate.");
  981. error.start_column = prev_pos;
  982. push_error(error);
  983. prev = 0;
  984. }
  985. }
  986. if (valid_escape) {
  987. result += escaped;
  988. }
  989. }
  990. } else if (ch == quote_char) {
  991. if (prev != 0) {
  992. Token error = make_error("Invalid UTF-16 sequence in string, unpaired lead surrogate");
  993. error.start_column = prev_pos;
  994. push_error(error);
  995. prev = 0;
  996. }
  997. _advance();
  998. if (is_multiline) {
  999. if (_peek() == quote_char && _peek(1) == quote_char) {
  1000. // Ended the multiline string. Consume all quotes.
  1001. _advance();
  1002. _advance();
  1003. break;
  1004. } else {
  1005. // Not a multiline string termination, add consumed quote.
  1006. result += quote_char;
  1007. }
  1008. } else {
  1009. // Ended single-line string.
  1010. break;
  1011. }
  1012. } else {
  1013. if (prev != 0) {
  1014. Token error = make_error("Invalid UTF-16 sequence in string, unpaired lead surrogate");
  1015. error.start_column = prev_pos;
  1016. push_error(error);
  1017. prev = 0;
  1018. }
  1019. result += ch;
  1020. _advance();
  1021. if (ch == '\n') {
  1022. newline(false);
  1023. }
  1024. }
  1025. }
  1026. if (prev != 0) {
  1027. Token error = make_error("Invalid UTF-16 sequence in string, unpaired lead surrogate");
  1028. error.start_column = prev_pos;
  1029. push_error(error);
  1030. prev = 0;
  1031. }
  1032. // Make the literal.
  1033. Variant string;
  1034. switch (type) {
  1035. case STRING_NAME:
  1036. string = StringName(result);
  1037. break;
  1038. case STRING_NODEPATH:
  1039. string = NodePath(result);
  1040. break;
  1041. case STRING_REGULAR:
  1042. string = result;
  1043. break;
  1044. }
  1045. return make_literal(string);
  1046. }
  1047. void GDScriptTokenizerText::check_indent() {
  1048. ERR_FAIL_COND_MSG(column != 1, "Checking tokenizer indentation in the middle of a line.");
  1049. if (_is_at_end()) {
  1050. // Send dedents for every indent level.
  1051. pending_indents -= indent_level();
  1052. indent_stack.clear();
  1053. return;
  1054. }
  1055. for (;;) {
  1056. char32_t current_indent_char = _peek();
  1057. int indent_count = 0;
  1058. if (current_indent_char != ' ' && current_indent_char != '\t' && current_indent_char != '\r' && current_indent_char != '\n' && current_indent_char != '#') {
  1059. // First character of the line is not whitespace, so we clear all indentation levels.
  1060. // Unless we are in a continuation or in multiline mode (inside expression).
  1061. if (line_continuation || multiline_mode) {
  1062. return;
  1063. }
  1064. pending_indents -= indent_level();
  1065. indent_stack.clear();
  1066. return;
  1067. }
  1068. if (_peek() == '\r') {
  1069. _advance();
  1070. if (_peek() != '\n') {
  1071. push_error("Stray carriage return character in source code.");
  1072. }
  1073. }
  1074. if (_peek() == '\n') {
  1075. // Empty line, keep going.
  1076. _advance();
  1077. newline(false);
  1078. continue;
  1079. }
  1080. // Check indent level.
  1081. bool mixed = false;
  1082. while (!_is_at_end()) {
  1083. char32_t space = _peek();
  1084. if (space == '\t') {
  1085. // Consider individual tab columns.
  1086. column += tab_size - 1;
  1087. indent_count += tab_size;
  1088. } else if (space == ' ') {
  1089. indent_count += 1;
  1090. } else {
  1091. break;
  1092. }
  1093. mixed = mixed || space != current_indent_char;
  1094. _advance();
  1095. }
  1096. if (_is_at_end()) {
  1097. // Reached the end with an empty line, so just dedent as much as needed.
  1098. pending_indents -= indent_level();
  1099. indent_stack.clear();
  1100. return;
  1101. }
  1102. if (_peek() == '\r') {
  1103. _advance();
  1104. if (_peek() != '\n') {
  1105. push_error("Stray carriage return character in source code.");
  1106. }
  1107. }
  1108. if (_peek() == '\n') {
  1109. // Empty line, keep going.
  1110. _advance();
  1111. newline(false);
  1112. continue;
  1113. }
  1114. if (_peek() == '#') {
  1115. // Comment. Advance to the next line.
  1116. #ifdef TOOLS_ENABLED
  1117. String comment;
  1118. while (_peek() != '\n' && !_is_at_end()) {
  1119. comment += _advance();
  1120. }
  1121. comments[line] = CommentData(comment, true);
  1122. #else
  1123. while (_peek() != '\n' && !_is_at_end()) {
  1124. _advance();
  1125. }
  1126. #endif // TOOLS_ENABLED
  1127. if (_is_at_end()) {
  1128. // Reached the end with an empty line, so just dedent as much as needed.
  1129. pending_indents -= indent_level();
  1130. indent_stack.clear();
  1131. return;
  1132. }
  1133. _advance(); // Consume '\n'.
  1134. newline(false);
  1135. continue;
  1136. }
  1137. if (mixed && !line_continuation && !multiline_mode) {
  1138. Token error = make_error("Mixed use of tabs and spaces for indentation.");
  1139. error.start_line = line;
  1140. error.start_column = 1;
  1141. push_error(error);
  1142. }
  1143. if (line_continuation || multiline_mode) {
  1144. // We cleared up all the whitespace at the beginning of the line.
  1145. // If this is a line continuation or we're in multiline mode then we don't want any indentation changes.
  1146. return;
  1147. }
  1148. // Check if indentation character is consistent.
  1149. if (indent_char == '\0') {
  1150. // First time indenting, choose character now.
  1151. indent_char = current_indent_char;
  1152. } else if (current_indent_char != indent_char) {
  1153. Token error = make_error(vformat("Used %s character for indentation instead of %s as used before in the file.",
  1154. _get_indent_char_name(current_indent_char), _get_indent_char_name(indent_char)));
  1155. error.start_line = line;
  1156. error.start_column = 1;
  1157. push_error(error);
  1158. }
  1159. // Now we can do actual indentation changes.
  1160. // Check if indent or dedent.
  1161. int previous_indent = 0;
  1162. if (indent_level() > 0) {
  1163. previous_indent = indent_stack.back()->get();
  1164. }
  1165. if (indent_count == previous_indent) {
  1166. // No change in indentation.
  1167. return;
  1168. }
  1169. if (indent_count > previous_indent) {
  1170. // Indentation increased.
  1171. indent_stack.push_back(indent_count);
  1172. pending_indents++;
  1173. } else {
  1174. // Indentation decreased (dedent).
  1175. if (indent_level() == 0) {
  1176. push_error("Tokenizer bug: trying to dedent without previous indent.");
  1177. return;
  1178. }
  1179. while (indent_level() > 0 && indent_stack.back()->get() > indent_count) {
  1180. indent_stack.pop_back();
  1181. pending_indents--;
  1182. }
  1183. if ((indent_level() > 0 && indent_stack.back()->get() != indent_count) || (indent_level() == 0 && indent_count != 0)) {
  1184. // Mismatched indentation alignment.
  1185. Token error = make_error("Unindent doesn't match the previous indentation level.");
  1186. error.start_line = line;
  1187. error.start_column = 1;
  1188. error.end_column = column + 1;
  1189. push_error(error);
  1190. // Still, we'll be lenient and keep going, so keep this level in the stack.
  1191. indent_stack.push_back(indent_count);
  1192. }
  1193. }
  1194. break; // Get out of the loop in any case.
  1195. }
  1196. }
  1197. String GDScriptTokenizerText::_get_indent_char_name(char32_t ch) {
  1198. ERR_FAIL_COND_V(ch != ' ' && ch != '\t', String::chr(ch).c_escape());
  1199. return ch == ' ' ? "space" : "tab";
  1200. }
  1201. void GDScriptTokenizerText::_skip_whitespace() {
  1202. if (pending_indents != 0) {
  1203. // Still have some indent/dedent tokens to give.
  1204. return;
  1205. }
  1206. bool is_bol = column == 1; // Beginning of line.
  1207. if (is_bol) {
  1208. check_indent();
  1209. return;
  1210. }
  1211. for (;;) {
  1212. char32_t c = _peek();
  1213. switch (c) {
  1214. case ' ':
  1215. _advance();
  1216. break;
  1217. case '\t':
  1218. _advance();
  1219. // Consider individual tab columns.
  1220. column += tab_size - 1;
  1221. break;
  1222. case '\r':
  1223. _advance(); // Consume either way.
  1224. if (_peek() != '\n') {
  1225. push_error("Stray carriage return character in source code.");
  1226. return;
  1227. }
  1228. break;
  1229. case '\n':
  1230. _advance();
  1231. newline(!is_bol); // Don't create new line token if line is empty.
  1232. check_indent();
  1233. break;
  1234. case '#': {
  1235. // Comment.
  1236. #ifdef TOOLS_ENABLED
  1237. String comment;
  1238. while (_peek() != '\n' && !_is_at_end()) {
  1239. comment += _advance();
  1240. }
  1241. comments[line] = CommentData(comment, is_bol);
  1242. #else
  1243. while (_peek() != '\n' && !_is_at_end()) {
  1244. _advance();
  1245. }
  1246. #endif // TOOLS_ENABLED
  1247. if (_is_at_end()) {
  1248. return;
  1249. }
  1250. _advance(); // Consume '\n'
  1251. newline(!is_bol);
  1252. check_indent();
  1253. } break;
  1254. default:
  1255. return;
  1256. }
  1257. }
  1258. }
  1259. GDScriptTokenizer::Token GDScriptTokenizerText::scan() {
  1260. if (has_error()) {
  1261. return pop_error();
  1262. }
  1263. _skip_whitespace();
  1264. if (pending_newline) {
  1265. pending_newline = false;
  1266. if (!multiline_mode) {
  1267. // Don't return newline tokens on multiline mode.
  1268. return last_newline;
  1269. }
  1270. }
  1271. // Check for potential errors after skipping whitespace().
  1272. if (has_error()) {
  1273. return pop_error();
  1274. }
  1275. _start = _current;
  1276. start_line = line;
  1277. start_column = column;
  1278. if (pending_indents != 0) {
  1279. // Adjust position for indent.
  1280. _start -= start_column - 1;
  1281. start_column = 1;
  1282. if (pending_indents > 0) {
  1283. // Indents.
  1284. pending_indents--;
  1285. return make_token(Token::INDENT);
  1286. } else {
  1287. // Dedents.
  1288. pending_indents++;
  1289. Token dedent = make_token(Token::DEDENT);
  1290. dedent.end_column += 1;
  1291. return dedent;
  1292. }
  1293. }
  1294. if (_is_at_end()) {
  1295. return make_token(Token::TK_EOF);
  1296. }
  1297. const char32_t c = _advance();
  1298. if (c == '\\') {
  1299. // Line continuation with backslash.
  1300. if (_peek() == '\r') {
  1301. if (_peek(1) != '\n') {
  1302. return make_error("Unexpected carriage return character.");
  1303. }
  1304. _advance();
  1305. }
  1306. if (_peek() != '\n') {
  1307. return make_error("Expected new line after \"\\\".");
  1308. }
  1309. _advance();
  1310. newline(false);
  1311. line_continuation = true;
  1312. _skip_whitespace(); // Skip whitespace/comment lines after `\`. See GH-89403.
  1313. continuation_lines.push_back(line);
  1314. return scan(); // Recurse to get next token.
  1315. }
  1316. line_continuation = false;
  1317. if (is_digit(c)) {
  1318. return number();
  1319. } else if (c == 'r' && (_peek() == '"' || _peek() == '\'')) {
  1320. // Raw string literals.
  1321. return string();
  1322. } else if (is_unicode_identifier_start(c)) {
  1323. return potential_identifier();
  1324. }
  1325. switch (c) {
  1326. // String literals.
  1327. case '"':
  1328. case '\'':
  1329. return string();
  1330. // Annotation.
  1331. case '@':
  1332. return annotation();
  1333. // Single characters.
  1334. case '~':
  1335. return make_token(Token::TILDE);
  1336. case ',':
  1337. return make_token(Token::COMMA);
  1338. case ':':
  1339. return make_token(Token::COLON);
  1340. case ';':
  1341. return make_token(Token::SEMICOLON);
  1342. case '$':
  1343. return make_token(Token::DOLLAR);
  1344. case '?':
  1345. return make_token(Token::QUESTION_MARK);
  1346. case '`':
  1347. return make_token(Token::BACKTICK);
  1348. // Parens.
  1349. case '(':
  1350. push_paren('(');
  1351. return make_token(Token::PARENTHESIS_OPEN);
  1352. case '[':
  1353. push_paren('[');
  1354. return make_token(Token::BRACKET_OPEN);
  1355. case '{':
  1356. push_paren('{');
  1357. return make_token(Token::BRACE_OPEN);
  1358. case ')':
  1359. if (!pop_paren('(')) {
  1360. return make_paren_error(c);
  1361. }
  1362. return make_token(Token::PARENTHESIS_CLOSE);
  1363. case ']':
  1364. if (!pop_paren('[')) {
  1365. return make_paren_error(c);
  1366. }
  1367. return make_token(Token::BRACKET_CLOSE);
  1368. case '}':
  1369. if (!pop_paren('{')) {
  1370. return make_paren_error(c);
  1371. }
  1372. return make_token(Token::BRACE_CLOSE);
  1373. // Double characters.
  1374. case '!':
  1375. if (_peek() == '=') {
  1376. _advance();
  1377. return make_token(Token::BANG_EQUAL);
  1378. } else {
  1379. return make_token(Token::BANG);
  1380. }
  1381. case '.':
  1382. if (_peek() == '.') {
  1383. _advance();
  1384. if (_peek() == '.') {
  1385. _advance();
  1386. return make_token(Token::PERIOD_PERIOD_PERIOD);
  1387. }
  1388. return make_token(Token::PERIOD_PERIOD);
  1389. } else if (is_digit(_peek())) {
  1390. // Number starting with '.'.
  1391. return number();
  1392. } else {
  1393. return make_token(Token::PERIOD);
  1394. }
  1395. case '+':
  1396. if (_peek() == '=') {
  1397. _advance();
  1398. return make_token(Token::PLUS_EQUAL);
  1399. } else if (is_digit(_peek()) && !last_token.can_precede_bin_op()) {
  1400. // Number starting with '+'.
  1401. return number();
  1402. } else {
  1403. return make_token(Token::PLUS);
  1404. }
  1405. case '-':
  1406. if (_peek() == '=') {
  1407. _advance();
  1408. return make_token(Token::MINUS_EQUAL);
  1409. } else if (is_digit(_peek()) && !last_token.can_precede_bin_op()) {
  1410. // Number starting with '-'.
  1411. return number();
  1412. } else if (_peek() == '>') {
  1413. _advance();
  1414. return make_token(Token::FORWARD_ARROW);
  1415. } else {
  1416. return make_token(Token::MINUS);
  1417. }
  1418. case '*':
  1419. if (_peek() == '=') {
  1420. _advance();
  1421. return make_token(Token::STAR_EQUAL);
  1422. } else if (_peek() == '*') {
  1423. if (_peek(1) == '=') {
  1424. _advance();
  1425. _advance(); // Advance both '*' and '='
  1426. return make_token(Token::STAR_STAR_EQUAL);
  1427. }
  1428. _advance();
  1429. return make_token(Token::STAR_STAR);
  1430. } else {
  1431. return make_token(Token::STAR);
  1432. }
  1433. case '/':
  1434. if (_peek() == '=') {
  1435. _advance();
  1436. return make_token(Token::SLASH_EQUAL);
  1437. } else {
  1438. return make_token(Token::SLASH);
  1439. }
  1440. case '%':
  1441. if (_peek() == '=') {
  1442. _advance();
  1443. return make_token(Token::PERCENT_EQUAL);
  1444. } else {
  1445. return make_token(Token::PERCENT);
  1446. }
  1447. case '^':
  1448. if (_peek() == '=') {
  1449. _advance();
  1450. return make_token(Token::CARET_EQUAL);
  1451. } else if (_peek() == '"' || _peek() == '\'') {
  1452. // Node path
  1453. return string();
  1454. } else {
  1455. return make_token(Token::CARET);
  1456. }
  1457. case '&':
  1458. if (_peek() == '&') {
  1459. _advance();
  1460. return make_token(Token::AMPERSAND_AMPERSAND);
  1461. } else if (_peek() == '=') {
  1462. _advance();
  1463. return make_token(Token::AMPERSAND_EQUAL);
  1464. } else if (_peek() == '"' || _peek() == '\'') {
  1465. // String Name
  1466. return string();
  1467. } else {
  1468. return make_token(Token::AMPERSAND);
  1469. }
  1470. case '|':
  1471. if (_peek() == '|') {
  1472. _advance();
  1473. return make_token(Token::PIPE_PIPE);
  1474. } else if (_peek() == '=') {
  1475. _advance();
  1476. return make_token(Token::PIPE_EQUAL);
  1477. } else {
  1478. return make_token(Token::PIPE);
  1479. }
  1480. // Potential VCS conflict markers.
  1481. case '=':
  1482. if (_peek() == '=') {
  1483. return check_vcs_marker('=', Token::EQUAL_EQUAL);
  1484. } else {
  1485. return make_token(Token::EQUAL);
  1486. }
  1487. case '<':
  1488. if (_peek() == '=') {
  1489. _advance();
  1490. return make_token(Token::LESS_EQUAL);
  1491. } else if (_peek() == '<') {
  1492. if (_peek(1) == '=') {
  1493. _advance();
  1494. _advance(); // Advance both '<' and '='
  1495. return make_token(Token::LESS_LESS_EQUAL);
  1496. } else {
  1497. return check_vcs_marker('<', Token::LESS_LESS);
  1498. }
  1499. } else {
  1500. return make_token(Token::LESS);
  1501. }
  1502. case '>':
  1503. if (_peek() == '=') {
  1504. _advance();
  1505. return make_token(Token::GREATER_EQUAL);
  1506. } else if (_peek() == '>') {
  1507. if (_peek(1) == '=') {
  1508. _advance();
  1509. _advance(); // Advance both '>' and '='
  1510. return make_token(Token::GREATER_GREATER_EQUAL);
  1511. } else {
  1512. return check_vcs_marker('>', Token::GREATER_GREATER);
  1513. }
  1514. } else {
  1515. return make_token(Token::GREATER);
  1516. }
  1517. default:
  1518. if (is_whitespace(c)) {
  1519. return make_error(vformat(R"(Invalid white space character U+%04X.)", static_cast<int32_t>(c)));
  1520. } else {
  1521. return make_error(vformat(R"(Invalid character "%c" (U+%04X).)", c, static_cast<int32_t>(c)));
  1522. }
  1523. }
  1524. }
  1525. GDScriptTokenizerText::GDScriptTokenizerText() {
  1526. #ifdef TOOLS_ENABLED
  1527. if (EditorSettings::get_singleton()) {
  1528. tab_size = EditorSettings::get_singleton()->get_setting("text_editor/behavior/indent/size");
  1529. }
  1530. #endif // TOOLS_ENABLED
  1531. #ifdef DEBUG_ENABLED
  1532. make_keyword_list();
  1533. #endif // DEBUG_ENABLED
  1534. }