gdscript_tokenizer.cpp 45 KB

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