shader_preprocessor.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422
  1. /**************************************************************************/
  2. /* shader_preprocessor.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 "shader_preprocessor.h"
  31. #include "core/math/expression.h"
  32. const char32_t CURSOR = 0xFFFF;
  33. // Tokenizer
  34. void ShaderPreprocessor::Tokenizer::add_generated(const ShaderPreprocessor::Token &p_t) {
  35. generated.push_back(p_t);
  36. }
  37. char32_t ShaderPreprocessor::Tokenizer::next() {
  38. if (index < size) {
  39. return code[index++];
  40. }
  41. return 0;
  42. }
  43. int ShaderPreprocessor::Tokenizer::get_line() const {
  44. return line;
  45. }
  46. int ShaderPreprocessor::Tokenizer::get_index() const {
  47. return index;
  48. }
  49. void ShaderPreprocessor::Tokenizer::get_and_clear_generated(LocalVector<char32_t> *r_out) {
  50. for (uint32_t i = 0; i < generated.size(); i++) {
  51. r_out->push_back(generated[i].text);
  52. }
  53. generated.clear();
  54. }
  55. void ShaderPreprocessor::Tokenizer::backtrack(char32_t p_what) {
  56. while (index >= 0) {
  57. char32_t c = code[index];
  58. if (c == p_what) {
  59. break;
  60. }
  61. index--;
  62. }
  63. }
  64. char32_t ShaderPreprocessor::Tokenizer::peek() {
  65. if (index < size) {
  66. return code[index];
  67. }
  68. return 0;
  69. }
  70. int ShaderPreprocessor::Tokenizer::consume_line_continuations(int p_offset) {
  71. int skips = 0;
  72. for (int i = index + p_offset; i < size; i++) {
  73. char32_t c = code[i];
  74. if (c == '\\') {
  75. if (i + 1 < size && code[i + 1] == '\n') {
  76. // This line ends with "\" and "\n" continuation.
  77. add_generated(Token('\n', line));
  78. line++;
  79. skips++;
  80. i = i + 2;
  81. index = i;
  82. } else {
  83. break;
  84. }
  85. } else if (!is_whitespace(c)) {
  86. break;
  87. }
  88. }
  89. return skips;
  90. }
  91. LocalVector<ShaderPreprocessor::Token> ShaderPreprocessor::Tokenizer::advance(char32_t p_what) {
  92. LocalVector<ShaderPreprocessor::Token> tokens;
  93. while (index < size) {
  94. char32_t c = code[index++];
  95. if (c == '\\' && consume_line_continuations(-1) > 0) {
  96. continue;
  97. }
  98. if (c == '\n') {
  99. add_generated(ShaderPreprocessor::Token('\n', line));
  100. line++;
  101. }
  102. tokens.push_back(ShaderPreprocessor::Token(c, line));
  103. if (c == p_what || c == 0) {
  104. return tokens;
  105. }
  106. }
  107. return LocalVector<ShaderPreprocessor::Token>();
  108. }
  109. void ShaderPreprocessor::Tokenizer::skip_whitespace() {
  110. while (is_char_space(peek())) {
  111. next();
  112. }
  113. }
  114. bool ShaderPreprocessor::Tokenizer::consume_empty_line() {
  115. // Read until newline and return true if the content was all whitespace/empty.
  116. return tokens_to_string(advance('\n')).strip_edges().size() == 0;
  117. }
  118. String ShaderPreprocessor::Tokenizer::get_identifier(bool *r_is_cursor, bool p_started) {
  119. if (r_is_cursor != nullptr) {
  120. *r_is_cursor = false;
  121. }
  122. LocalVector<char32_t> text;
  123. while (true) {
  124. char32_t c = peek();
  125. if (c == '\\' && consume_line_continuations(0) > 0) {
  126. continue;
  127. }
  128. if (is_char_end(c) || c == '(' || c == ')' || c == ',' || c == ';') {
  129. break;
  130. }
  131. if (is_whitespace(c) && p_started) {
  132. break;
  133. }
  134. if (!is_whitespace(c)) {
  135. p_started = true;
  136. }
  137. char32_t n = next();
  138. if (n == CURSOR) {
  139. if (r_is_cursor != nullptr) {
  140. *r_is_cursor = true;
  141. }
  142. } else {
  143. if (p_started) {
  144. text.push_back(n);
  145. }
  146. }
  147. }
  148. String id = vector_to_string(text);
  149. if (!id.is_valid_ascii_identifier()) {
  150. return "";
  151. }
  152. return id;
  153. }
  154. String ShaderPreprocessor::Tokenizer::peek_identifier() {
  155. const int original = index;
  156. const int original_line = line;
  157. String id = get_identifier();
  158. index = original;
  159. line = original_line;
  160. return id;
  161. }
  162. ShaderPreprocessor::Token ShaderPreprocessor::Tokenizer::get_token() {
  163. while (index < size) {
  164. const char32_t c = code[index++];
  165. const Token t = ShaderPreprocessor::Token(c, line);
  166. switch (c) {
  167. case ' ':
  168. case '\t':
  169. skip_whitespace();
  170. return ShaderPreprocessor::Token(' ', line);
  171. case '\n':
  172. line++;
  173. return t;
  174. default:
  175. return t;
  176. }
  177. }
  178. return ShaderPreprocessor::Token(char32_t(0), line);
  179. }
  180. ShaderPreprocessor::Tokenizer::Tokenizer(const String &p_code) {
  181. code = p_code;
  182. line = 0;
  183. index = 0;
  184. size = code.size();
  185. }
  186. // ShaderPreprocessor::CommentRemover
  187. String ShaderPreprocessor::CommentRemover::get_error() const {
  188. if (comments_open != 0) {
  189. return "Block comment mismatch";
  190. }
  191. return "";
  192. }
  193. int ShaderPreprocessor::CommentRemover::get_error_line() const {
  194. if (comments_open != 0) {
  195. return comment_line_open;
  196. }
  197. return -1;
  198. }
  199. char32_t ShaderPreprocessor::CommentRemover::peek() const {
  200. if (index < code.size()) {
  201. return code[index];
  202. }
  203. return 0;
  204. }
  205. bool ShaderPreprocessor::CommentRemover::advance(char32_t p_what) {
  206. while (index < code.size()) {
  207. char32_t c = code[index++];
  208. if (c == '\n') {
  209. line++;
  210. stripped.push_back('\n');
  211. }
  212. if (c == p_what) {
  213. return true;
  214. }
  215. }
  216. return false;
  217. }
  218. String ShaderPreprocessor::CommentRemover::strip() {
  219. stripped.clear();
  220. index = 0;
  221. line = 0;
  222. comment_line_open = 0;
  223. comments_open = 0;
  224. strings_open = 0;
  225. while (index < code.size()) {
  226. char32_t c = code[index++];
  227. if (c == CURSOR) {
  228. // Cursor. Maintain.
  229. stripped.push_back(c);
  230. } else if (c == '"') {
  231. if (strings_open <= 0) {
  232. strings_open++;
  233. } else {
  234. strings_open--;
  235. }
  236. stripped.push_back(c);
  237. } else if (c == '/' && strings_open == 0) {
  238. char32_t p = peek();
  239. if (p == '/') { // Single line comment.
  240. advance('\n');
  241. } else if (p == '*') { // Start of a block comment.
  242. index++;
  243. comment_line_open = line;
  244. comments_open++;
  245. while (advance('*')) {
  246. if (peek() == '/') { // End of a block comment.
  247. comments_open--;
  248. index++;
  249. break;
  250. }
  251. }
  252. } else {
  253. stripped.push_back(c);
  254. }
  255. } else if (c == '*' && strings_open == 0) {
  256. if (peek() == '/') { // Unmatched end of a block comment.
  257. comment_line_open = line;
  258. comments_open--;
  259. } else {
  260. stripped.push_back(c);
  261. }
  262. } else if (c == '\n') {
  263. line++;
  264. stripped.push_back(c);
  265. } else {
  266. stripped.push_back(c);
  267. }
  268. }
  269. return vector_to_string(stripped);
  270. }
  271. ShaderPreprocessor::CommentRemover::CommentRemover(const String &p_code) {
  272. code = p_code;
  273. index = 0;
  274. line = 0;
  275. comment_line_open = 0;
  276. comments_open = 0;
  277. strings_open = 0;
  278. }
  279. // ShaderPreprocessor::Token
  280. ShaderPreprocessor::Token::Token() {
  281. text = 0;
  282. line = -1;
  283. }
  284. ShaderPreprocessor::Token::Token(char32_t p_text, int p_line) {
  285. text = p_text;
  286. line = p_line;
  287. }
  288. // ShaderPreprocessor
  289. bool ShaderPreprocessor::is_char_word(char32_t p_char) {
  290. if ((p_char >= '0' && p_char <= '9') ||
  291. (p_char >= 'a' && p_char <= 'z') ||
  292. (p_char >= 'A' && p_char <= 'Z') ||
  293. p_char == '_') {
  294. return true;
  295. }
  296. return false;
  297. }
  298. bool ShaderPreprocessor::is_char_space(char32_t p_char) {
  299. return p_char == ' ' || p_char == '\t';
  300. }
  301. bool ShaderPreprocessor::is_char_end(char32_t p_char) {
  302. return p_char == '\n' || p_char == 0;
  303. }
  304. String ShaderPreprocessor::vector_to_string(const LocalVector<char32_t> &p_v, int p_start, int p_end) {
  305. const int stop = (p_end == -1) ? p_v.size() : p_end;
  306. const int count = stop - p_start;
  307. String result;
  308. result.resize(count + 1);
  309. for (int i = 0; i < count; i++) {
  310. result[i] = p_v[p_start + i];
  311. }
  312. result[count] = 0; // Ensure string is null terminated for length() to work.
  313. return result;
  314. }
  315. String ShaderPreprocessor::tokens_to_string(const LocalVector<Token> &p_tokens) {
  316. LocalVector<char32_t> result;
  317. for (const Token &token : p_tokens) {
  318. result.push_back(token.text);
  319. }
  320. return vector_to_string(result);
  321. }
  322. void ShaderPreprocessor::process_directive(Tokenizer *p_tokenizer) {
  323. bool is_cursor;
  324. String directive = p_tokenizer->get_identifier(&is_cursor, true);
  325. if (is_cursor) {
  326. state->completion_type = COMPLETION_TYPE_DIRECTIVE;
  327. }
  328. if (directive == "if") {
  329. process_if(p_tokenizer);
  330. } else if (directive == "ifdef") {
  331. process_ifdef(p_tokenizer);
  332. } else if (directive == "ifndef") {
  333. process_ifndef(p_tokenizer);
  334. } else if (directive == "elif") {
  335. process_elif(p_tokenizer);
  336. } else if (directive == "else") {
  337. process_else(p_tokenizer);
  338. } else if (directive == "endif") {
  339. process_endif(p_tokenizer);
  340. } else if (directive == "error") {
  341. process_error(p_tokenizer);
  342. } else if (directive == "define") {
  343. process_define(p_tokenizer);
  344. } else if (directive == "undef") {
  345. process_undef(p_tokenizer);
  346. } else if (directive == "include") {
  347. process_include(p_tokenizer);
  348. } else if (directive == "pragma") {
  349. process_pragma(p_tokenizer);
  350. } else {
  351. set_error(RTR("Unknown directive."), p_tokenizer->get_line());
  352. }
  353. }
  354. void ShaderPreprocessor::process_define(Tokenizer *p_tokenizer) {
  355. const int line = p_tokenizer->get_line();
  356. String label = p_tokenizer->get_identifier();
  357. if (label.is_empty()) {
  358. set_error(RTR("Invalid macro name."), line);
  359. return;
  360. }
  361. if (state->defines.has(label)) {
  362. set_error(RTR("Macro redefinition."), line);
  363. return;
  364. }
  365. Vector<String> args;
  366. if (p_tokenizer->peek() == '(') {
  367. // Macro has arguments.
  368. p_tokenizer->get_token();
  369. while (true) {
  370. String name = p_tokenizer->get_identifier();
  371. if (name.is_empty()) {
  372. set_error(RTR("Invalid argument name."), line);
  373. return;
  374. }
  375. args.push_back(name);
  376. p_tokenizer->skip_whitespace();
  377. char32_t next = p_tokenizer->get_token().text;
  378. if (next == ')') {
  379. break;
  380. } else if (next != ',') {
  381. set_error(RTR("Expected a comma in the macro argument list."), line);
  382. return;
  383. }
  384. }
  385. }
  386. String body = tokens_to_string(p_tokenizer->advance('\n')).strip_edges();
  387. if (body.begins_with("##")) {
  388. set_error(RTR("'##' must not appear at beginning of macro expansion."), line);
  389. return;
  390. }
  391. if (body.ends_with("##")) {
  392. set_error(RTR("'##' must not appear at end of macro expansion."), line);
  393. return;
  394. }
  395. Define *define = memnew(Define);
  396. if (!args.is_empty()) {
  397. define->arguments = args;
  398. }
  399. define->body = body;
  400. state->defines[label] = define;
  401. }
  402. void ShaderPreprocessor::process_elif(Tokenizer *p_tokenizer) {
  403. const int line = p_tokenizer->get_line();
  404. if (state->current_branch == nullptr || state->current_branch->else_defined) {
  405. set_error(vformat(RTR("Unmatched '%s' directive."), "elif"), line);
  406. return;
  407. }
  408. if (state->previous_region != nullptr) {
  409. state->previous_region->to_line = line - 1;
  410. }
  411. String body = tokens_to_string(p_tokenizer->advance('\n')).strip_edges();
  412. if (body.is_empty()) {
  413. set_error(RTR("Missing condition."), line);
  414. return;
  415. }
  416. Error error = expand_condition(body, line, body);
  417. if (error != OK) {
  418. return;
  419. }
  420. error = expand_macros(body, line, body);
  421. if (error != OK) {
  422. return;
  423. }
  424. Expression expression;
  425. Vector<String> names;
  426. error = expression.parse(body, names);
  427. if (error != OK) {
  428. set_error(expression.get_error_text(), line);
  429. return;
  430. }
  431. Variant v = expression.execute(Array(), nullptr, false);
  432. if (v.get_type() == Variant::NIL) {
  433. set_error(RTR("Condition evaluation error."), line);
  434. return;
  435. }
  436. bool skip = false;
  437. for (int i = 0; i < state->current_branch->conditions.size(); i++) {
  438. if (state->current_branch->conditions[i]) {
  439. skip = true;
  440. break;
  441. }
  442. }
  443. bool success = !skip && v.booleanize();
  444. start_branch_condition(p_tokenizer, success, true);
  445. if (state->save_regions) {
  446. add_region(line + 1, success, state->previous_region->parent);
  447. }
  448. }
  449. void ShaderPreprocessor::process_else(Tokenizer *p_tokenizer) {
  450. const int line = p_tokenizer->get_line();
  451. if (state->current_branch == nullptr || state->current_branch->else_defined) {
  452. set_error(vformat(RTR("Unmatched '%s' directive."), "else"), line);
  453. return;
  454. }
  455. if (state->previous_region != nullptr) {
  456. state->previous_region->to_line = line - 1;
  457. }
  458. if (!p_tokenizer->consume_empty_line()) {
  459. set_error(vformat(RTR("Invalid '%s' directive."), "else"), line);
  460. }
  461. bool skip = false;
  462. for (int i = 0; i < state->current_branch->conditions.size(); i++) {
  463. if (state->current_branch->conditions[i]) {
  464. skip = true;
  465. break;
  466. }
  467. }
  468. state->current_branch->else_defined = true;
  469. if (state->save_regions) {
  470. add_region(line + 1, !skip, state->previous_region->parent);
  471. }
  472. if (skip) {
  473. Vector<String> ends;
  474. ends.push_back("endif");
  475. next_directive(p_tokenizer, ends);
  476. }
  477. }
  478. void ShaderPreprocessor::process_endif(Tokenizer *p_tokenizer) {
  479. const int line = p_tokenizer->get_line();
  480. state->condition_depth--;
  481. if (state->condition_depth < 0) {
  482. set_error(vformat(RTR("Unmatched '%s' directive."), "endif"), line);
  483. return;
  484. }
  485. if (state->previous_region != nullptr) {
  486. state->previous_region->to_line = line - 1;
  487. state->previous_region = state->previous_region->parent;
  488. }
  489. if (!p_tokenizer->consume_empty_line()) {
  490. set_error(vformat(RTR("Invalid '%s' directive."), "endif"), line);
  491. }
  492. state->current_branch = state->current_branch->parent;
  493. state->branches.pop_back();
  494. }
  495. void ShaderPreprocessor::process_error(Tokenizer *p_tokenizer) {
  496. const int line = p_tokenizer->get_line();
  497. const String body = tokens_to_string(p_tokenizer->advance('\n')).strip_edges();
  498. if (body.is_empty()) {
  499. set_error(" ", line);
  500. } else {
  501. set_error(body, line);
  502. }
  503. if (!p_tokenizer->consume_empty_line()) {
  504. set_error(vformat(RTR("Invalid '%s' directive."), "error"), line);
  505. }
  506. }
  507. void ShaderPreprocessor::process_if(Tokenizer *p_tokenizer) {
  508. const int line = p_tokenizer->get_line();
  509. String body = tokens_to_string(p_tokenizer->advance('\n')).strip_edges();
  510. if (body.is_empty()) {
  511. set_error(RTR("Missing condition."), line);
  512. return;
  513. }
  514. Error error = expand_condition(body, line, body);
  515. if (error != OK) {
  516. return;
  517. }
  518. error = expand_macros(body, line, body);
  519. if (error != OK) {
  520. return;
  521. }
  522. Expression expression;
  523. Vector<String> names;
  524. error = expression.parse(body, names);
  525. if (error != OK) {
  526. set_error(expression.get_error_text(), line);
  527. return;
  528. }
  529. Variant v = expression.execute(Array(), nullptr, false);
  530. if (v.get_type() == Variant::NIL) {
  531. set_error(RTR("Condition evaluation error."), line);
  532. return;
  533. }
  534. bool success = v.booleanize();
  535. start_branch_condition(p_tokenizer, success);
  536. if (state->save_regions) {
  537. add_region(line + 1, success, state->previous_region);
  538. }
  539. }
  540. void ShaderPreprocessor::process_ifdef(Tokenizer *p_tokenizer) {
  541. const int line = p_tokenizer->get_line();
  542. String label = p_tokenizer->get_identifier();
  543. if (label.is_empty()) {
  544. set_error(RTR("Invalid macro name."), line);
  545. return;
  546. }
  547. if (!p_tokenizer->consume_empty_line()) {
  548. set_error(vformat(RTR("Invalid '%s' directive."), "ifdef"), line);
  549. return;
  550. }
  551. bool success = state->defines.has(label);
  552. start_branch_condition(p_tokenizer, success);
  553. if (state->save_regions) {
  554. add_region(line + 1, success, state->previous_region);
  555. }
  556. }
  557. void ShaderPreprocessor::process_ifndef(Tokenizer *p_tokenizer) {
  558. const int line = p_tokenizer->get_line();
  559. String label = p_tokenizer->get_identifier();
  560. if (label.is_empty()) {
  561. set_error(RTR("Invalid macro name."), line);
  562. return;
  563. }
  564. if (!p_tokenizer->consume_empty_line()) {
  565. set_error(vformat(RTR("Invalid '%s' directive."), "ifndef"), line);
  566. return;
  567. }
  568. bool success = !state->defines.has(label);
  569. start_branch_condition(p_tokenizer, success);
  570. if (state->save_regions) {
  571. add_region(line + 1, success, state->previous_region);
  572. }
  573. }
  574. void ShaderPreprocessor::process_include(Tokenizer *p_tokenizer) {
  575. const int line = p_tokenizer->get_line();
  576. p_tokenizer->advance('"');
  577. String path = tokens_to_string(p_tokenizer->advance('"'));
  578. for (int i = 0; i < path.length(); i++) {
  579. if (path[i] == '\n') {
  580. break; //stop parsing
  581. }
  582. if (path[i] == CURSOR) {
  583. state->completion_type = COMPLETION_TYPE_INCLUDE_PATH;
  584. break;
  585. }
  586. }
  587. path = path.substr(0, path.length() - 1);
  588. if (path.is_empty() || !p_tokenizer->consume_empty_line()) {
  589. set_error(RTR("Invalid path."), line);
  590. return;
  591. }
  592. path = path.simplify_path();
  593. if (path.is_relative_path()) {
  594. path = state->current_filename.get_base_dir().path_join(path);
  595. }
  596. if (!ResourceLoader::exists(path)) {
  597. set_error(RTR("Shader include file does not exist:") + " " + path, line);
  598. return;
  599. }
  600. Ref<Resource> res = ResourceLoader::load(path);
  601. if (res.is_null()) {
  602. set_error(RTR("Shader include load failed. Does the shader include exist? Is there a cyclic dependency?"), line);
  603. return;
  604. }
  605. Ref<ShaderInclude> shader_inc = res;
  606. if (shader_inc.is_null()) {
  607. set_error(RTR("Shader include resource type is wrong."), line);
  608. return;
  609. }
  610. String included = shader_inc->get_code();
  611. if (!included.is_empty()) {
  612. uint64_t code_hash = included.hash64();
  613. if (state->cyclic_include_hashes.find(code_hash)) {
  614. set_error(RTR("Cyclic include found") + ": " + path, line);
  615. return;
  616. }
  617. }
  618. state->shader_includes.insert(shader_inc);
  619. const String real_path = shader_inc->get_path();
  620. if (state->includes.has(real_path)) {
  621. // Already included, skip.
  622. // This is a valid check because 2 separate include paths could use some
  623. // of the same shared functions from a common shader include.
  624. return;
  625. }
  626. // Mark as included.
  627. state->includes.insert(real_path);
  628. state->include_depth++;
  629. if (state->include_depth > 25) {
  630. set_error(RTR("Shader max include depth exceeded."), line);
  631. return;
  632. }
  633. String old_filename = state->current_filename;
  634. state->current_filename = real_path;
  635. ShaderPreprocessor processor;
  636. int prev_condition_depth = state->condition_depth;
  637. state->condition_depth = 0;
  638. FilePosition fp;
  639. fp.file = state->current_filename;
  640. fp.line = line + 1;
  641. state->include_positions.push_back(fp);
  642. String result;
  643. processor.preprocess(state, included, result);
  644. add_to_output("@@>" + real_path + "\n"); // Add token for enter include path
  645. add_to_output(result);
  646. add_to_output("\n@@<" + real_path + "\n"); // Add token for exit include path.
  647. // Reset to last include if there are no errors. We want to use this as context.
  648. if (state->error.is_empty()) {
  649. state->current_filename = old_filename;
  650. state->include_positions.pop_back();
  651. } else {
  652. return;
  653. }
  654. state->include_depth--;
  655. state->condition_depth = prev_condition_depth;
  656. }
  657. void ShaderPreprocessor::process_pragma(Tokenizer *p_tokenizer) {
  658. const int line = p_tokenizer->get_line();
  659. bool is_cursor;
  660. const String label = p_tokenizer->get_identifier(&is_cursor);
  661. if (is_cursor) {
  662. state->completion_type = COMPLETION_TYPE_PRAGMA;
  663. }
  664. if (label.is_empty()) {
  665. set_error(vformat(RTR("Invalid '%s' directive."), "pragma"), line);
  666. return;
  667. }
  668. // Explicitly handle pragma values here.
  669. // If more pragma options are created, then refactor into a more defined structure.
  670. if (label == "disable_preprocessor") {
  671. state->disabled = true;
  672. } else {
  673. set_error(vformat(RTR("Invalid '%s' directive."), "pragma"), line);
  674. return;
  675. }
  676. if (!p_tokenizer->consume_empty_line()) {
  677. set_error(vformat(RTR("Invalid '%s' directive."), "pragma"), line);
  678. return;
  679. }
  680. }
  681. void ShaderPreprocessor::process_undef(Tokenizer *p_tokenizer) {
  682. const int line = p_tokenizer->get_line();
  683. const String label = p_tokenizer->get_identifier();
  684. if (label.is_empty() || !p_tokenizer->consume_empty_line()) {
  685. set_error(vformat(RTR("Invalid '%s' directive."), "undef"), line);
  686. return;
  687. }
  688. if (state->defines.has(label)) {
  689. memdelete(state->defines[label]);
  690. state->defines.erase(label);
  691. }
  692. }
  693. void ShaderPreprocessor::add_region(int p_line, bool p_enabled, Region *p_parent_region) {
  694. Region region;
  695. region.file = state->current_filename;
  696. region.enabled = p_enabled;
  697. region.from_line = p_line;
  698. region.parent = p_parent_region;
  699. state->previous_region = &state->regions[region.file].push_back(region)->get();
  700. }
  701. void ShaderPreprocessor::start_branch_condition(Tokenizer *p_tokenizer, bool p_success, bool p_continue) {
  702. if (!p_continue) {
  703. state->condition_depth++;
  704. state->current_branch = &state->branches.push_back(Branch(p_success, state->current_branch))->get();
  705. } else {
  706. state->current_branch->conditions.push_back(p_success);
  707. }
  708. if (!p_success) {
  709. Vector<String> ends;
  710. ends.push_back("elif");
  711. ends.push_back("else");
  712. ends.push_back("endif");
  713. next_directive(p_tokenizer, ends);
  714. }
  715. }
  716. void ShaderPreprocessor::expand_output_macros(int p_start, int p_line_number) {
  717. String line = vector_to_string(output, p_start, output.size());
  718. Error error = expand_macros(line, p_line_number - 1, line); // We are already on next line, so -1.
  719. if (error != OK) {
  720. return;
  721. }
  722. output.resize(p_start);
  723. add_to_output(line);
  724. }
  725. Error ShaderPreprocessor::expand_condition(const String &p_string, int p_line, String &r_expanded) {
  726. // Checks bracket count to be even + check the cursor position.
  727. {
  728. int bracket_start_count = 0;
  729. int bracket_end_count = 0;
  730. for (int i = 0; i < p_string.size(); i++) {
  731. switch (p_string[i]) {
  732. case CURSOR:
  733. state->completion_type = COMPLETION_TYPE_CONDITION;
  734. break;
  735. case '(':
  736. bracket_start_count++;
  737. break;
  738. case ')':
  739. bracket_end_count++;
  740. break;
  741. }
  742. }
  743. if (bracket_start_count > bracket_end_count) {
  744. _set_expected_error(")", p_line);
  745. return FAILED;
  746. }
  747. if (bracket_end_count > bracket_start_count) {
  748. _set_expected_error("(", p_line);
  749. return FAILED;
  750. }
  751. }
  752. String result = p_string;
  753. int index = 0;
  754. int index_start = 0;
  755. int index_end = 0;
  756. while (find_match(result, "defined", index, index_start)) {
  757. bool open_bracket = false;
  758. bool found_word = false;
  759. bool word_completed = false;
  760. LocalVector<char32_t> text;
  761. int post_bracket_index = -1;
  762. int size = result.size();
  763. for (int i = (index_start - 1); i < size; i++) {
  764. char32_t c = result[i];
  765. if (c == 0) {
  766. if (found_word) {
  767. word_completed = true;
  768. }
  769. break;
  770. }
  771. char32_t cs[] = { c, '\0' };
  772. String s = String(cs);
  773. bool is_space = is_char_space(c);
  774. if (word_completed) {
  775. if (c == ')') {
  776. continue;
  777. }
  778. if (c == '|' || c == '&') {
  779. if (open_bracket) {
  780. _set_unexpected_token_error(s, p_line);
  781. return FAILED;
  782. }
  783. break;
  784. } else if (!is_space) {
  785. _set_unexpected_token_error(s, p_line);
  786. return FAILED;
  787. }
  788. } else if (is_space) {
  789. if (found_word && !open_bracket) {
  790. index_end = i;
  791. word_completed = true;
  792. }
  793. } else if (c == '(') {
  794. if (open_bracket) {
  795. _set_unexpected_token_error(s, p_line);
  796. return FAILED;
  797. }
  798. open_bracket = true;
  799. } else if (c == ')') {
  800. if (open_bracket) {
  801. if (!found_word) {
  802. _set_unexpected_token_error(s, p_line);
  803. return FAILED;
  804. }
  805. open_bracket = false;
  806. post_bracket_index = i + 1;
  807. } else {
  808. index_end = i;
  809. }
  810. word_completed = true;
  811. } else if (is_char_word(c)) {
  812. text.push_back(c);
  813. found_word = true;
  814. } else {
  815. _set_unexpected_token_error(s, p_line);
  816. return FAILED;
  817. }
  818. }
  819. if (word_completed) {
  820. if (open_bracket) {
  821. _set_expected_error(")", p_line);
  822. return FAILED;
  823. }
  824. if (post_bracket_index != -1) {
  825. index_end = post_bracket_index;
  826. }
  827. String body = state->defines.has(vector_to_string(text)) ? "true" : "false";
  828. String temp = result;
  829. result = result.substr(0, index) + body;
  830. index_start = result.length();
  831. if (index_end > 0) {
  832. result += temp.substr(index_end);
  833. }
  834. } else {
  835. set_error(RTR("Invalid macro name."), p_line);
  836. return FAILED;
  837. }
  838. }
  839. r_expanded = result;
  840. return OK;
  841. }
  842. Error ShaderPreprocessor::expand_macros(const String &p_string, int p_line, String &r_expanded) {
  843. String iterative = p_string;
  844. int pass_count = 0;
  845. bool expanded = true;
  846. while (expanded) {
  847. expanded = false;
  848. // As long as we find something to expand, keep going.
  849. for (const RBMap<String, Define *>::Element *E = state->defines.front(); E; E = E->next()) {
  850. if (expand_macros_once(iterative, p_line, E, iterative)) {
  851. expanded = true;
  852. }
  853. }
  854. pass_count++;
  855. if (pass_count > 50) {
  856. set_error(RTR("Macro expansion limit exceeded."), p_line);
  857. break;
  858. }
  859. }
  860. r_expanded = iterative;
  861. if (!state->error.is_empty()) {
  862. return FAILED;
  863. }
  864. return OK;
  865. }
  866. bool ShaderPreprocessor::expand_macros_once(const String &p_line, int p_line_number, const RBMap<String, Define *>::Element *p_define_pair, String &r_expanded) {
  867. String result = p_line;
  868. const String &key = p_define_pair->key();
  869. const Define *define = p_define_pair->value();
  870. int index_start = 0;
  871. int index = 0;
  872. if (find_match(result, key, index, index_start)) {
  873. String body = define->body;
  874. if (define->arguments.size() > 0) {
  875. // Complex macro with arguments.
  876. int args_start = -1;
  877. int args_end = -1;
  878. int brackets_open = 0;
  879. Vector<String> args;
  880. for (int i = index_start - 1; i < p_line.length(); i++) {
  881. bool add_argument = false;
  882. bool reached_end = false;
  883. char32_t c = p_line[i];
  884. if (c == '(') {
  885. brackets_open++;
  886. if (brackets_open == 1) {
  887. args_start = i + 1;
  888. args_end = -1;
  889. }
  890. } else if (c == ')') {
  891. brackets_open--;
  892. if (brackets_open == 0) {
  893. args_end = i;
  894. add_argument = true;
  895. reached_end = true;
  896. }
  897. } else if (c == ',') {
  898. if (brackets_open == 1) {
  899. args_end = i;
  900. add_argument = true;
  901. }
  902. }
  903. if (add_argument) {
  904. if (args_start == -1 || args_end == -1) {
  905. set_error(RTR("Invalid macro argument list."), p_line_number);
  906. return false;
  907. }
  908. String arg = p_line.substr(args_start, args_end - args_start).strip_edges();
  909. if (arg.is_empty()) {
  910. set_error(RTR("Invalid macro argument."), p_line_number);
  911. return false;
  912. }
  913. args.append(arg);
  914. args_start = args_end + 1;
  915. }
  916. if (reached_end) {
  917. break;
  918. }
  919. }
  920. if (args.size() != define->arguments.size()) {
  921. set_error(RTR("Invalid macro argument count."), p_line_number);
  922. return false;
  923. }
  924. // Insert macro arguments into the body.
  925. for (int i = 0; i < args.size(); i++) {
  926. String arg_name = define->arguments[i];
  927. int arg_index_start = 0;
  928. int arg_index = 0;
  929. while (find_match(body, arg_name, arg_index, arg_index_start)) {
  930. body = body.substr(0, arg_index) + args[i] + body.substr(arg_index + arg_name.length(), body.length() - (arg_index + arg_name.length()));
  931. // Manually reset arg_index_start to where the arg value of the define finishes.
  932. // This ensures we don't skip the other args of this macro in the string.
  933. arg_index_start = arg_index + args[i].length() + 1;
  934. }
  935. }
  936. concatenate_macro_body(body);
  937. result = result.substr(0, index) + " " + body + " " + result.substr(args_end + 1, result.length());
  938. } else {
  939. concatenate_macro_body(body);
  940. result = result.substr(0, index) + " " + body + " " + result.substr(index + key.length(), result.length() - (index + key.length()));
  941. }
  942. r_expanded = result;
  943. return true;
  944. }
  945. return false;
  946. }
  947. bool ShaderPreprocessor::find_match(const String &p_string, const String &p_value, int &r_index, int &r_index_start) {
  948. // Looks for value in string and then determines if the boundaries
  949. // are non-word characters. This method semi-emulates \b in regex.
  950. r_index = p_string.find(p_value, r_index_start);
  951. while (r_index > -1) {
  952. if (r_index > 0) {
  953. if (is_char_word(p_string[r_index - 1])) {
  954. r_index_start = r_index + 1;
  955. r_index = p_string.find(p_value, r_index_start);
  956. continue;
  957. }
  958. }
  959. if (r_index + p_value.length() < p_string.length()) {
  960. if (is_char_word(p_string[r_index + p_value.length()])) {
  961. r_index_start = r_index + p_value.length() + 1;
  962. r_index = p_string.find(p_value, r_index_start);
  963. continue;
  964. }
  965. }
  966. // Return and shift index start automatically for next call.
  967. r_index_start = r_index + p_value.length() + 1;
  968. return true;
  969. }
  970. return false;
  971. }
  972. void ShaderPreprocessor::concatenate_macro_body(String &r_body) {
  973. int index_start = r_body.find("##");
  974. while (index_start > -1) {
  975. int index_end = index_start + 2; // First character after ##.
  976. // The macro was checked during creation so this should never happen.
  977. ERR_FAIL_INDEX(index_end, r_body.size());
  978. // If there more than two # in a row, then it's not a concatenation.
  979. bool is_concat = true;
  980. while (index_end <= r_body.length() && r_body[index_end] == '#') {
  981. index_end++;
  982. is_concat = false;
  983. }
  984. if (!is_concat) {
  985. index_start = r_body.find("##", index_end);
  986. continue;
  987. }
  988. // Skip whitespace after ##.
  989. while (index_end < r_body.length() && is_char_space(r_body[index_end])) {
  990. index_end++;
  991. }
  992. // Skip whitespace before ##.
  993. while (index_start >= 1 && is_char_space(r_body[index_start - 1])) {
  994. index_start--;
  995. }
  996. r_body = r_body.substr(0, index_start) + r_body.substr(index_end, r_body.length() - index_end);
  997. index_start = r_body.find("##", index_start);
  998. }
  999. }
  1000. String ShaderPreprocessor::next_directive(Tokenizer *p_tokenizer, const Vector<String> &p_directives) {
  1001. const int line = p_tokenizer->get_line();
  1002. int nesting = 0;
  1003. while (true) {
  1004. p_tokenizer->advance('#');
  1005. String id = p_tokenizer->peek_identifier();
  1006. if (id.is_empty()) {
  1007. break;
  1008. }
  1009. if (nesting == 0) {
  1010. for (int i = 0; i < p_directives.size(); i++) {
  1011. if (p_directives[i] == id) {
  1012. p_tokenizer->backtrack('#');
  1013. return id;
  1014. }
  1015. }
  1016. }
  1017. if (id == "ifdef" || id == "ifndef" || id == "if") {
  1018. nesting++;
  1019. } else if (id == "endif") {
  1020. nesting--;
  1021. }
  1022. }
  1023. set_error(RTR("Can't find matching branch directive."), line);
  1024. return "";
  1025. }
  1026. void ShaderPreprocessor::add_to_output(const String &p_str) {
  1027. for (int i = 0; i < p_str.length(); i++) {
  1028. output.push_back(p_str[i]);
  1029. }
  1030. }
  1031. void ShaderPreprocessor::set_error(const String &p_error, int p_line) {
  1032. if (state->error.is_empty()) {
  1033. state->error = p_error;
  1034. FilePosition fp;
  1035. fp.file = state->current_filename;
  1036. fp.line = p_line + 1;
  1037. state->include_positions.push_back(fp);
  1038. }
  1039. }
  1040. ShaderPreprocessor::Define *ShaderPreprocessor::create_define(const String &p_body) {
  1041. ShaderPreprocessor::Define *define = memnew(Define);
  1042. define->body = p_body;
  1043. return define;
  1044. }
  1045. void ShaderPreprocessor::clear_state() {
  1046. if (state != nullptr) {
  1047. for (const RBMap<String, Define *>::Element *E = state->defines.front(); E; E = E->next()) {
  1048. memdelete(E->get());
  1049. }
  1050. state->defines.clear();
  1051. }
  1052. state = nullptr;
  1053. }
  1054. Error ShaderPreprocessor::preprocess(State *p_state, const String &p_code, String &r_result) {
  1055. output.clear();
  1056. state = p_state;
  1057. CommentRemover remover(p_code);
  1058. String stripped = remover.strip();
  1059. String error = remover.get_error();
  1060. if (!error.is_empty()) {
  1061. set_error(error, remover.get_error_line());
  1062. return FAILED;
  1063. }
  1064. // Track code hashes to prevent cyclic include.
  1065. uint64_t code_hash = p_code.hash64();
  1066. state->cyclic_include_hashes.push_back(code_hash);
  1067. Tokenizer p_tokenizer(stripped);
  1068. int last_size = 0;
  1069. bool has_symbols_before_directive = false;
  1070. while (true) {
  1071. const Token &t = p_tokenizer.get_token();
  1072. if (t.text == 0) {
  1073. break;
  1074. }
  1075. // Add autogenerated tokens if there are any.
  1076. p_tokenizer.get_and_clear_generated(&output);
  1077. if (state->disabled) {
  1078. // Preprocessor was disabled.
  1079. // Read the rest of the file into the output.
  1080. output.push_back(t.text);
  1081. continue;
  1082. }
  1083. if (t.text == '#') {
  1084. if (has_symbols_before_directive) {
  1085. set_error(RTR("Invalid symbols placed before directive."), p_tokenizer.get_line());
  1086. state->cyclic_include_hashes.erase(code_hash); // Remove this hash.
  1087. return FAILED;
  1088. }
  1089. process_directive(&p_tokenizer);
  1090. } else {
  1091. if (is_char_end(t.text)) {
  1092. expand_output_macros(last_size, p_tokenizer.get_line());
  1093. last_size = output.size();
  1094. has_symbols_before_directive = false;
  1095. } else if (!is_char_space(t.text)) {
  1096. has_symbols_before_directive = true;
  1097. }
  1098. output.push_back(t.text);
  1099. }
  1100. if (!state->error.is_empty()) {
  1101. state->cyclic_include_hashes.erase(code_hash); // Remove this hash.
  1102. return FAILED;
  1103. }
  1104. }
  1105. state->cyclic_include_hashes.erase(code_hash); // Remove this hash.
  1106. if (!state->disabled) {
  1107. if (state->condition_depth != 0) {
  1108. set_error(RTR("Unmatched conditional statement."), p_tokenizer.line);
  1109. return FAILED;
  1110. }
  1111. expand_output_macros(last_size, p_tokenizer.get_line());
  1112. }
  1113. r_result = vector_to_string(output);
  1114. return OK;
  1115. }
  1116. Error ShaderPreprocessor::preprocess(const String &p_code, const String &p_filename, String &r_result, String *r_error_text, List<FilePosition> *r_error_position, List<Region> *r_regions, HashSet<Ref<ShaderInclude>> *r_includes, List<ScriptLanguage::CodeCompletionOption> *r_completion_options, List<ScriptLanguage::CodeCompletionOption> *r_completion_defines, IncludeCompletionFunction p_include_completion_func) {
  1117. State pp_state;
  1118. if (!p_filename.is_empty()) {
  1119. pp_state.current_filename = p_filename;
  1120. pp_state.save_regions = r_regions != nullptr;
  1121. }
  1122. Error err = preprocess(&pp_state, p_code, r_result);
  1123. if (err != OK) {
  1124. if (r_error_text) {
  1125. *r_error_text = pp_state.error;
  1126. }
  1127. if (r_error_position) {
  1128. *r_error_position = pp_state.include_positions;
  1129. }
  1130. }
  1131. if (r_regions) {
  1132. *r_regions = pp_state.regions[p_filename];
  1133. }
  1134. if (r_includes) {
  1135. *r_includes = pp_state.shader_includes;
  1136. }
  1137. if (r_completion_defines) {
  1138. for (const KeyValue<String, Define *> &E : state->defines) {
  1139. ScriptLanguage::CodeCompletionOption option(E.key, ScriptLanguage::CODE_COMPLETION_KIND_CONSTANT);
  1140. r_completion_defines->push_back(option);
  1141. }
  1142. }
  1143. if (r_completion_options) {
  1144. switch (pp_state.completion_type) {
  1145. case COMPLETION_TYPE_DIRECTIVE: {
  1146. List<String> options;
  1147. get_keyword_list(&options, true, true);
  1148. for (const String &E : options) {
  1149. ScriptLanguage::CodeCompletionOption option(E, ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT);
  1150. r_completion_options->push_back(option);
  1151. }
  1152. } break;
  1153. case COMPLETION_TYPE_PRAGMA: {
  1154. List<String> options;
  1155. ShaderPreprocessor::get_pragma_list(&options);
  1156. for (const String &E : options) {
  1157. ScriptLanguage::CodeCompletionOption option(E, ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT);
  1158. r_completion_options->push_back(option);
  1159. }
  1160. } break;
  1161. case COMPLETION_TYPE_CONDITION: {
  1162. ScriptLanguage::CodeCompletionOption option("defined", ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT);
  1163. r_completion_options->push_back(option);
  1164. } break;
  1165. case COMPLETION_TYPE_INCLUDE_PATH: {
  1166. if (p_include_completion_func && r_completion_options) {
  1167. p_include_completion_func(r_completion_options);
  1168. }
  1169. } break;
  1170. default: {
  1171. }
  1172. }
  1173. }
  1174. clear_state();
  1175. return err;
  1176. }
  1177. void ShaderPreprocessor::get_keyword_list(List<String> *r_keywords, bool p_include_shader_keywords, bool p_ignore_context_keywords) {
  1178. r_keywords->push_back("define");
  1179. if (!p_ignore_context_keywords) {
  1180. r_keywords->push_back("defined");
  1181. }
  1182. r_keywords->push_back("elif");
  1183. if (p_include_shader_keywords) {
  1184. r_keywords->push_back("else");
  1185. }
  1186. r_keywords->push_back("endif");
  1187. r_keywords->push_back("error");
  1188. if (p_include_shader_keywords) {
  1189. r_keywords->push_back("if");
  1190. }
  1191. r_keywords->push_back("ifdef");
  1192. r_keywords->push_back("ifndef");
  1193. r_keywords->push_back("include");
  1194. r_keywords->push_back("pragma");
  1195. r_keywords->push_back("undef");
  1196. }
  1197. void ShaderPreprocessor::get_pragma_list(List<String> *r_pragmas) {
  1198. r_pragmas->push_back("disable_preprocessor");
  1199. }
  1200. ShaderPreprocessor::ShaderPreprocessor() {
  1201. }
  1202. ShaderPreprocessor::~ShaderPreprocessor() {
  1203. }