shader_preprocessor.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405
  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_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 == "define") {
  341. process_define(p_tokenizer);
  342. } else if (directive == "undef") {
  343. process_undef(p_tokenizer);
  344. } else if (directive == "include") {
  345. process_include(p_tokenizer);
  346. } else if (directive == "pragma") {
  347. process_pragma(p_tokenizer);
  348. } else {
  349. set_error(RTR("Unknown directive."), p_tokenizer->get_line());
  350. }
  351. }
  352. void ShaderPreprocessor::process_define(Tokenizer *p_tokenizer) {
  353. const int line = p_tokenizer->get_line();
  354. String label = p_tokenizer->get_identifier();
  355. if (label.is_empty()) {
  356. set_error(RTR("Invalid macro name."), line);
  357. return;
  358. }
  359. if (state->defines.has(label)) {
  360. set_error(RTR("Macro redefinition."), line);
  361. return;
  362. }
  363. Vector<String> args;
  364. if (p_tokenizer->peek() == '(') {
  365. // Macro has arguments.
  366. p_tokenizer->get_token();
  367. while (true) {
  368. String name = p_tokenizer->get_identifier();
  369. if (name.is_empty()) {
  370. set_error(RTR("Invalid argument name."), line);
  371. return;
  372. }
  373. args.push_back(name);
  374. p_tokenizer->skip_whitespace();
  375. char32_t next = p_tokenizer->get_token().text;
  376. if (next == ')') {
  377. break;
  378. } else if (next != ',') {
  379. set_error(RTR("Expected a comma in the macro argument list."), line);
  380. return;
  381. }
  382. }
  383. }
  384. String body = tokens_to_string(p_tokenizer->advance('\n')).strip_edges();
  385. if (body.begins_with("##")) {
  386. set_error(RTR("'##' must not appear at beginning of macro expansion."), line);
  387. return;
  388. }
  389. if (body.ends_with("##")) {
  390. set_error(RTR("'##' must not appear at end of macro expansion."), line);
  391. return;
  392. }
  393. Define *define = memnew(Define);
  394. if (!args.is_empty()) {
  395. define->arguments = args;
  396. }
  397. define->body = body;
  398. state->defines[label] = define;
  399. }
  400. void ShaderPreprocessor::process_elif(Tokenizer *p_tokenizer) {
  401. const int line = p_tokenizer->get_line();
  402. if (state->current_branch == nullptr || state->current_branch->else_defined) {
  403. set_error(RTR("Unmatched elif."), line);
  404. return;
  405. }
  406. if (state->previous_region != nullptr) {
  407. state->previous_region->to_line = line - 1;
  408. }
  409. String body = tokens_to_string(p_tokenizer->advance('\n')).strip_edges();
  410. if (body.is_empty()) {
  411. set_error(RTR("Missing condition."), line);
  412. return;
  413. }
  414. Error error = expand_condition(body, line, body);
  415. if (error != OK) {
  416. return;
  417. }
  418. error = expand_macros(body, line, body);
  419. if (error != OK) {
  420. return;
  421. }
  422. Expression expression;
  423. Vector<String> names;
  424. error = expression.parse(body, names);
  425. if (error != OK) {
  426. set_error(expression.get_error_text(), line);
  427. return;
  428. }
  429. Variant v = expression.execute(Array(), nullptr, false);
  430. if (v.get_type() == Variant::NIL) {
  431. set_error(RTR("Condition evaluation error."), line);
  432. return;
  433. }
  434. bool skip = false;
  435. for (int i = 0; i < state->current_branch->conditions.size(); i++) {
  436. if (state->current_branch->conditions[i]) {
  437. skip = true;
  438. break;
  439. }
  440. }
  441. bool success = !skip && v.booleanize();
  442. start_branch_condition(p_tokenizer, success, true);
  443. if (state->save_regions) {
  444. add_region(line + 1, success, state->previous_region->parent);
  445. }
  446. }
  447. void ShaderPreprocessor::process_else(Tokenizer *p_tokenizer) {
  448. const int line = p_tokenizer->get_line();
  449. if (state->current_branch == nullptr || state->current_branch->else_defined) {
  450. set_error(RTR("Unmatched else."), line);
  451. return;
  452. }
  453. if (state->previous_region != nullptr) {
  454. state->previous_region->to_line = line - 1;
  455. }
  456. if (!p_tokenizer->consume_empty_line()) {
  457. set_error(RTR("Invalid else."), p_tokenizer->get_line());
  458. }
  459. bool skip = false;
  460. for (int i = 0; i < state->current_branch->conditions.size(); i++) {
  461. if (state->current_branch->conditions[i]) {
  462. skip = true;
  463. break;
  464. }
  465. }
  466. state->current_branch->else_defined = true;
  467. if (state->save_regions) {
  468. add_region(line + 1, !skip, state->previous_region->parent);
  469. }
  470. if (skip) {
  471. Vector<String> ends;
  472. ends.push_back("endif");
  473. next_directive(p_tokenizer, ends);
  474. }
  475. }
  476. void ShaderPreprocessor::process_endif(Tokenizer *p_tokenizer) {
  477. const int line = p_tokenizer->get_line();
  478. state->condition_depth--;
  479. if (state->condition_depth < 0) {
  480. set_error(RTR("Unmatched endif."), line);
  481. return;
  482. }
  483. if (state->previous_region != nullptr) {
  484. state->previous_region->to_line = line - 1;
  485. state->previous_region = state->previous_region->parent;
  486. }
  487. if (!p_tokenizer->consume_empty_line()) {
  488. set_error(RTR("Invalid endif."), line);
  489. }
  490. state->current_branch = state->current_branch->parent;
  491. state->branches.pop_back();
  492. }
  493. void ShaderPreprocessor::process_if(Tokenizer *p_tokenizer) {
  494. const int line = p_tokenizer->get_line();
  495. String body = tokens_to_string(p_tokenizer->advance('\n')).strip_edges();
  496. if (body.is_empty()) {
  497. set_error(RTR("Missing condition."), line);
  498. return;
  499. }
  500. Error error = expand_condition(body, line, body);
  501. if (error != OK) {
  502. return;
  503. }
  504. error = expand_macros(body, line, body);
  505. if (error != OK) {
  506. return;
  507. }
  508. Expression expression;
  509. Vector<String> names;
  510. error = expression.parse(body, names);
  511. if (error != OK) {
  512. set_error(expression.get_error_text(), line);
  513. return;
  514. }
  515. Variant v = expression.execute(Array(), nullptr, false);
  516. if (v.get_type() == Variant::NIL) {
  517. set_error(RTR("Condition evaluation error."), line);
  518. return;
  519. }
  520. bool success = v.booleanize();
  521. start_branch_condition(p_tokenizer, success);
  522. if (state->save_regions) {
  523. add_region(line + 1, success, state->previous_region);
  524. }
  525. }
  526. void ShaderPreprocessor::process_ifdef(Tokenizer *p_tokenizer) {
  527. const int line = p_tokenizer->get_line();
  528. String label = p_tokenizer->get_identifier();
  529. if (label.is_empty()) {
  530. set_error(RTR("Invalid macro name."), line);
  531. return;
  532. }
  533. if (!p_tokenizer->consume_empty_line()) {
  534. set_error(RTR("Invalid ifdef."), line);
  535. return;
  536. }
  537. bool success = state->defines.has(label);
  538. start_branch_condition(p_tokenizer, success);
  539. if (state->save_regions) {
  540. add_region(line + 1, success, state->previous_region);
  541. }
  542. }
  543. void ShaderPreprocessor::process_ifndef(Tokenizer *p_tokenizer) {
  544. const int line = p_tokenizer->get_line();
  545. String label = p_tokenizer->get_identifier();
  546. if (label.is_empty()) {
  547. set_error(RTR("Invalid macro name."), line);
  548. return;
  549. }
  550. if (!p_tokenizer->consume_empty_line()) {
  551. set_error(RTR("Invalid ifndef."), line);
  552. return;
  553. }
  554. bool success = !state->defines.has(label);
  555. start_branch_condition(p_tokenizer, success);
  556. if (state->save_regions) {
  557. add_region(line + 1, success, state->previous_region);
  558. }
  559. }
  560. void ShaderPreprocessor::process_include(Tokenizer *p_tokenizer) {
  561. const int line = p_tokenizer->get_line();
  562. p_tokenizer->advance('"');
  563. String path = tokens_to_string(p_tokenizer->advance('"'));
  564. for (int i = 0; i < path.length(); i++) {
  565. if (path[i] == '\n') {
  566. break; //stop parsing
  567. }
  568. if (path[i] == CURSOR) {
  569. state->completion_type = COMPLETION_TYPE_INCLUDE_PATH;
  570. break;
  571. }
  572. }
  573. path = path.substr(0, path.length() - 1);
  574. if (path.is_empty() || !p_tokenizer->consume_empty_line()) {
  575. set_error(RTR("Invalid path."), line);
  576. return;
  577. }
  578. path = path.simplify_path();
  579. if (path.is_relative_path()) {
  580. path = state->current_filename.get_base_dir().path_join(path);
  581. }
  582. if (!ResourceLoader::exists(path)) {
  583. set_error(RTR("Shader include file does not exist:") + " " + path, line);
  584. return;
  585. }
  586. Ref<Resource> res = ResourceLoader::load(path);
  587. if (res.is_null()) {
  588. set_error(RTR("Shader include load failed. Does the shader include exist? Is there a cyclic dependency?"), line);
  589. return;
  590. }
  591. Ref<ShaderInclude> shader_inc = res;
  592. if (shader_inc.is_null()) {
  593. set_error(RTR("Shader include resource type is wrong."), line);
  594. return;
  595. }
  596. String included = shader_inc->get_code();
  597. if (!included.is_empty()) {
  598. uint64_t code_hash = included.hash64();
  599. if (state->cyclic_include_hashes.find(code_hash)) {
  600. set_error(RTR("Cyclic include found") + ": " + path, line);
  601. return;
  602. }
  603. }
  604. state->shader_includes.insert(shader_inc);
  605. const String real_path = shader_inc->get_path();
  606. if (state->includes.has(real_path)) {
  607. // Already included, skip.
  608. // This is a valid check because 2 separate include paths could use some
  609. // of the same shared functions from a common shader include.
  610. return;
  611. }
  612. // Mark as included.
  613. state->includes.insert(real_path);
  614. state->include_depth++;
  615. if (state->include_depth > 25) {
  616. set_error(RTR("Shader max include depth exceeded."), line);
  617. return;
  618. }
  619. String old_filename = state->current_filename;
  620. state->current_filename = real_path;
  621. ShaderPreprocessor processor;
  622. int prev_condition_depth = state->condition_depth;
  623. state->condition_depth = 0;
  624. FilePosition fp;
  625. fp.file = state->current_filename;
  626. fp.line = line + 1;
  627. state->include_positions.push_back(fp);
  628. String result;
  629. processor.preprocess(state, included, result);
  630. add_to_output("@@>" + real_path + "\n"); // Add token for enter include path
  631. add_to_output(result);
  632. add_to_output("\n@@<" + real_path + "\n"); // Add token for exit include path.
  633. // Reset to last include if there are no errors. We want to use this as context.
  634. if (state->error.is_empty()) {
  635. state->current_filename = old_filename;
  636. state->include_positions.pop_back();
  637. } else {
  638. return;
  639. }
  640. state->include_depth--;
  641. state->condition_depth = prev_condition_depth;
  642. }
  643. void ShaderPreprocessor::process_pragma(Tokenizer *p_tokenizer) {
  644. const int line = p_tokenizer->get_line();
  645. bool is_cursor;
  646. const String label = p_tokenizer->get_identifier(&is_cursor);
  647. if (is_cursor) {
  648. state->completion_type = COMPLETION_TYPE_PRAGMA;
  649. }
  650. if (label.is_empty()) {
  651. set_error(RTR("Invalid pragma directive."), line);
  652. return;
  653. }
  654. // Rxplicitly handle pragma values here.
  655. // If more pragma options are created, then refactor into a more defined structure.
  656. if (label == "disable_preprocessor") {
  657. state->disabled = true;
  658. } else {
  659. set_error(RTR("Invalid pragma directive."), line);
  660. return;
  661. }
  662. if (!p_tokenizer->consume_empty_line()) {
  663. set_error(RTR("Invalid pragma directive."), line);
  664. return;
  665. }
  666. }
  667. void ShaderPreprocessor::process_undef(Tokenizer *p_tokenizer) {
  668. const int line = p_tokenizer->get_line();
  669. const String label = p_tokenizer->get_identifier();
  670. if (label.is_empty() || !p_tokenizer->consume_empty_line()) {
  671. set_error(RTR("Invalid undef."), line);
  672. return;
  673. }
  674. if (state->defines.has(label)) {
  675. memdelete(state->defines[label]);
  676. state->defines.erase(label);
  677. }
  678. }
  679. void ShaderPreprocessor::add_region(int p_line, bool p_enabled, Region *p_parent_region) {
  680. Region region;
  681. region.file = state->current_filename;
  682. region.enabled = p_enabled;
  683. region.from_line = p_line;
  684. region.parent = p_parent_region;
  685. state->previous_region = &state->regions[region.file].push_back(region)->get();
  686. }
  687. void ShaderPreprocessor::start_branch_condition(Tokenizer *p_tokenizer, bool p_success, bool p_continue) {
  688. if (!p_continue) {
  689. state->condition_depth++;
  690. state->current_branch = &state->branches.push_back(Branch(p_success, state->current_branch))->get();
  691. } else {
  692. state->current_branch->conditions.push_back(p_success);
  693. }
  694. if (!p_success) {
  695. Vector<String> ends;
  696. ends.push_back("elif");
  697. ends.push_back("else");
  698. ends.push_back("endif");
  699. next_directive(p_tokenizer, ends);
  700. }
  701. }
  702. void ShaderPreprocessor::expand_output_macros(int p_start, int p_line_number) {
  703. String line = vector_to_string(output, p_start, output.size());
  704. Error error = expand_macros(line, p_line_number - 1, line); // We are already on next line, so -1.
  705. if (error != OK) {
  706. return;
  707. }
  708. output.resize(p_start);
  709. add_to_output(line);
  710. }
  711. Error ShaderPreprocessor::expand_condition(const String &p_string, int p_line, String &r_expanded) {
  712. // Checks bracket count to be even + check the cursor position.
  713. {
  714. int bracket_start_count = 0;
  715. int bracket_end_count = 0;
  716. for (int i = 0; i < p_string.size(); i++) {
  717. switch (p_string[i]) {
  718. case CURSOR:
  719. state->completion_type = COMPLETION_TYPE_CONDITION;
  720. break;
  721. case '(':
  722. bracket_start_count++;
  723. break;
  724. case ')':
  725. bracket_end_count++;
  726. break;
  727. }
  728. }
  729. if (bracket_start_count > bracket_end_count) {
  730. _set_expected_error(")", p_line);
  731. return FAILED;
  732. }
  733. if (bracket_end_count > bracket_start_count) {
  734. _set_expected_error("(", p_line);
  735. return FAILED;
  736. }
  737. }
  738. String result = p_string;
  739. int index = 0;
  740. int index_start = 0;
  741. int index_end = 0;
  742. while (find_match(result, "defined", index, index_start)) {
  743. bool open_bracket = false;
  744. bool found_word = false;
  745. bool word_completed = false;
  746. LocalVector<char32_t> text;
  747. int post_bracket_index = -1;
  748. int size = result.size();
  749. for (int i = (index_start - 1); i < size; i++) {
  750. char32_t c = result[i];
  751. if (c == 0) {
  752. if (found_word) {
  753. word_completed = true;
  754. }
  755. break;
  756. }
  757. char32_t cs[] = { c, '\0' };
  758. String s = String(cs);
  759. bool is_space = is_char_space(c);
  760. if (word_completed) {
  761. if (c == ')') {
  762. continue;
  763. }
  764. if (c == '|' || c == '&') {
  765. if (open_bracket) {
  766. _set_unexpected_token_error(s, p_line);
  767. return FAILED;
  768. }
  769. break;
  770. } else if (!is_space) {
  771. _set_unexpected_token_error(s, p_line);
  772. return FAILED;
  773. }
  774. } else if (is_space) {
  775. if (found_word && !open_bracket) {
  776. index_end = i;
  777. word_completed = true;
  778. }
  779. } else if (c == '(') {
  780. if (open_bracket) {
  781. _set_unexpected_token_error(s, p_line);
  782. return FAILED;
  783. }
  784. open_bracket = true;
  785. } else if (c == ')') {
  786. if (open_bracket) {
  787. if (!found_word) {
  788. _set_unexpected_token_error(s, p_line);
  789. return FAILED;
  790. }
  791. open_bracket = false;
  792. post_bracket_index = i + 1;
  793. } else {
  794. index_end = i;
  795. }
  796. word_completed = true;
  797. } else if (is_char_word(c)) {
  798. text.push_back(c);
  799. found_word = true;
  800. } else {
  801. _set_unexpected_token_error(s, p_line);
  802. return FAILED;
  803. }
  804. }
  805. if (word_completed) {
  806. if (open_bracket) {
  807. _set_expected_error(")", p_line);
  808. return FAILED;
  809. }
  810. if (post_bracket_index != -1) {
  811. index_end = post_bracket_index;
  812. }
  813. String body = state->defines.has(vector_to_string(text)) ? "true" : "false";
  814. String temp = result;
  815. result = result.substr(0, index) + body;
  816. index_start = result.length();
  817. if (index_end > 0) {
  818. result += temp.substr(index_end);
  819. }
  820. } else {
  821. set_error(RTR("Invalid macro name."), p_line);
  822. return FAILED;
  823. }
  824. }
  825. r_expanded = result;
  826. return OK;
  827. }
  828. Error ShaderPreprocessor::expand_macros(const String &p_string, int p_line, String &r_expanded) {
  829. String iterative = p_string;
  830. int pass_count = 0;
  831. bool expanded = true;
  832. while (expanded) {
  833. expanded = false;
  834. // As long as we find something to expand, keep going.
  835. for (const RBMap<String, Define *>::Element *E = state->defines.front(); E; E = E->next()) {
  836. if (expand_macros_once(iterative, p_line, E, iterative)) {
  837. expanded = true;
  838. }
  839. }
  840. pass_count++;
  841. if (pass_count > 50) {
  842. set_error(RTR("Macro expansion limit exceeded."), p_line);
  843. break;
  844. }
  845. }
  846. r_expanded = iterative;
  847. if (!state->error.is_empty()) {
  848. return FAILED;
  849. }
  850. return OK;
  851. }
  852. bool ShaderPreprocessor::expand_macros_once(const String &p_line, int p_line_number, const RBMap<String, Define *>::Element *p_define_pair, String &r_expanded) {
  853. String result = p_line;
  854. const String &key = p_define_pair->key();
  855. const Define *define = p_define_pair->value();
  856. int index_start = 0;
  857. int index = 0;
  858. if (find_match(result, key, index, index_start)) {
  859. String body = define->body;
  860. if (define->arguments.size() > 0) {
  861. // Complex macro with arguments.
  862. int args_start = -1;
  863. int args_end = -1;
  864. int brackets_open = 0;
  865. Vector<String> args;
  866. for (int i = index_start - 1; i < p_line.length(); i++) {
  867. bool add_argument = false;
  868. bool reached_end = false;
  869. char32_t c = p_line[i];
  870. if (c == '(') {
  871. brackets_open++;
  872. if (brackets_open == 1) {
  873. args_start = i + 1;
  874. args_end = -1;
  875. }
  876. } else if (c == ')') {
  877. brackets_open--;
  878. if (brackets_open == 0) {
  879. args_end = i;
  880. add_argument = true;
  881. reached_end = true;
  882. }
  883. } else if (c == ',') {
  884. if (brackets_open == 1) {
  885. args_end = i;
  886. add_argument = true;
  887. }
  888. }
  889. if (add_argument) {
  890. if (args_start == -1 || args_end == -1) {
  891. set_error(RTR("Invalid macro argument list."), p_line_number);
  892. return false;
  893. }
  894. String arg = p_line.substr(args_start, args_end - args_start).strip_edges();
  895. if (arg.is_empty()) {
  896. set_error(RTR("Invalid macro argument."), p_line_number);
  897. return false;
  898. }
  899. args.append(arg);
  900. args_start = args_end + 1;
  901. }
  902. if (reached_end) {
  903. break;
  904. }
  905. }
  906. if (args.size() != define->arguments.size()) {
  907. set_error(RTR("Invalid macro argument count."), p_line_number);
  908. return false;
  909. }
  910. // Insert macro arguments into the body.
  911. for (int i = 0; i < args.size(); i++) {
  912. String arg_name = define->arguments[i];
  913. int arg_index_start = 0;
  914. int arg_index = 0;
  915. while (find_match(body, arg_name, arg_index, arg_index_start)) {
  916. body = body.substr(0, arg_index) + args[i] + body.substr(arg_index + arg_name.length(), body.length() - (arg_index + arg_name.length()));
  917. // Manually reset arg_index_start to where the arg value of the define finishes.
  918. // This ensures we don't skip the other args of this macro in the string.
  919. arg_index_start = arg_index + args[i].length() + 1;
  920. }
  921. }
  922. concatenate_macro_body(body);
  923. result = result.substr(0, index) + " " + body + " " + result.substr(args_end + 1, result.length());
  924. } else {
  925. concatenate_macro_body(body);
  926. result = result.substr(0, index) + " " + body + " " + result.substr(index + key.length(), result.length() - (index + key.length()));
  927. }
  928. r_expanded = result;
  929. return true;
  930. }
  931. return false;
  932. }
  933. bool ShaderPreprocessor::find_match(const String &p_string, const String &p_value, int &r_index, int &r_index_start) {
  934. // Looks for value in string and then determines if the boundaries
  935. // are non-word characters. This method semi-emulates \b in regex.
  936. r_index = p_string.find(p_value, r_index_start);
  937. while (r_index > -1) {
  938. if (r_index > 0) {
  939. if (is_char_word(p_string[r_index - 1])) {
  940. r_index_start = r_index + 1;
  941. r_index = p_string.find(p_value, r_index_start);
  942. continue;
  943. }
  944. }
  945. if (r_index + p_value.length() < p_string.length()) {
  946. if (is_char_word(p_string[r_index + p_value.length()])) {
  947. r_index_start = r_index + p_value.length() + 1;
  948. r_index = p_string.find(p_value, r_index_start);
  949. continue;
  950. }
  951. }
  952. // Return and shift index start automatically for next call.
  953. r_index_start = r_index + p_value.length() + 1;
  954. return true;
  955. }
  956. return false;
  957. }
  958. void ShaderPreprocessor::concatenate_macro_body(String &r_body) {
  959. int index_start = r_body.find("##");
  960. while (index_start > -1) {
  961. int index_end = index_start + 2; // First character after ##.
  962. // The macro was checked during creation so this should never happen.
  963. ERR_FAIL_INDEX(index_end, r_body.size());
  964. // If there more than two # in a row, then it's not a concatenation.
  965. bool is_concat = true;
  966. while (index_end <= r_body.length() && r_body[index_end] == '#') {
  967. index_end++;
  968. is_concat = false;
  969. }
  970. if (!is_concat) {
  971. index_start = r_body.find("##", index_end);
  972. continue;
  973. }
  974. // Skip whitespace after ##.
  975. while (index_end < r_body.length() && is_char_space(r_body[index_end])) {
  976. index_end++;
  977. }
  978. // Skip whitespace before ##.
  979. while (index_start >= 1 && is_char_space(r_body[index_start - 1])) {
  980. index_start--;
  981. }
  982. r_body = r_body.substr(0, index_start) + r_body.substr(index_end, r_body.length() - index_end);
  983. index_start = r_body.find("##", index_start);
  984. }
  985. }
  986. String ShaderPreprocessor::next_directive(Tokenizer *p_tokenizer, const Vector<String> &p_directives) {
  987. const int line = p_tokenizer->get_line();
  988. int nesting = 0;
  989. while (true) {
  990. p_tokenizer->advance('#');
  991. String id = p_tokenizer->peek_identifier();
  992. if (id.is_empty()) {
  993. break;
  994. }
  995. if (nesting == 0) {
  996. for (int i = 0; i < p_directives.size(); i++) {
  997. if (p_directives[i] == id) {
  998. p_tokenizer->backtrack('#');
  999. return id;
  1000. }
  1001. }
  1002. }
  1003. if (id == "ifdef" || id == "ifndef" || id == "if") {
  1004. nesting++;
  1005. } else if (id == "endif") {
  1006. nesting--;
  1007. }
  1008. }
  1009. set_error(RTR("Can't find matching branch directive."), line);
  1010. return "";
  1011. }
  1012. void ShaderPreprocessor::add_to_output(const String &p_str) {
  1013. for (int i = 0; i < p_str.length(); i++) {
  1014. output.push_back(p_str[i]);
  1015. }
  1016. }
  1017. void ShaderPreprocessor::set_error(const String &p_error, int p_line) {
  1018. if (state->error.is_empty()) {
  1019. state->error = p_error;
  1020. FilePosition fp;
  1021. fp.file = state->current_filename;
  1022. fp.line = p_line + 1;
  1023. state->include_positions.push_back(fp);
  1024. }
  1025. }
  1026. ShaderPreprocessor::Define *ShaderPreprocessor::create_define(const String &p_body) {
  1027. ShaderPreprocessor::Define *define = memnew(Define);
  1028. define->body = p_body;
  1029. return define;
  1030. }
  1031. void ShaderPreprocessor::clear_state() {
  1032. if (state != nullptr) {
  1033. for (const RBMap<String, Define *>::Element *E = state->defines.front(); E; E = E->next()) {
  1034. memdelete(E->get());
  1035. }
  1036. state->defines.clear();
  1037. }
  1038. state = nullptr;
  1039. }
  1040. Error ShaderPreprocessor::preprocess(State *p_state, const String &p_code, String &r_result) {
  1041. output.clear();
  1042. state = p_state;
  1043. CommentRemover remover(p_code);
  1044. String stripped = remover.strip();
  1045. String error = remover.get_error();
  1046. if (!error.is_empty()) {
  1047. set_error(error, remover.get_error_line());
  1048. return FAILED;
  1049. }
  1050. // Track code hashes to prevent cyclic include.
  1051. uint64_t code_hash = p_code.hash64();
  1052. state->cyclic_include_hashes.push_back(code_hash);
  1053. Tokenizer p_tokenizer(stripped);
  1054. int last_size = 0;
  1055. bool has_symbols_before_directive = false;
  1056. while (true) {
  1057. const Token &t = p_tokenizer.get_token();
  1058. if (t.text == 0) {
  1059. break;
  1060. }
  1061. // Add autogenerated tokens if there are any.
  1062. p_tokenizer.get_and_clear_generated(&output);
  1063. if (state->disabled) {
  1064. // Preprocessor was disabled.
  1065. // Read the rest of the file into the output.
  1066. output.push_back(t.text);
  1067. continue;
  1068. }
  1069. if (t.text == '#') {
  1070. if (has_symbols_before_directive) {
  1071. set_error(RTR("Invalid symbols placed before directive."), p_tokenizer.get_line());
  1072. state->cyclic_include_hashes.erase(code_hash); // Remove this hash.
  1073. return FAILED;
  1074. }
  1075. process_directive(&p_tokenizer);
  1076. } else {
  1077. if (is_char_end(t.text)) {
  1078. expand_output_macros(last_size, p_tokenizer.get_line());
  1079. last_size = output.size();
  1080. has_symbols_before_directive = false;
  1081. } else if (!is_char_space(t.text)) {
  1082. has_symbols_before_directive = true;
  1083. }
  1084. output.push_back(t.text);
  1085. }
  1086. if (!state->error.is_empty()) {
  1087. state->cyclic_include_hashes.erase(code_hash); // Remove this hash.
  1088. return FAILED;
  1089. }
  1090. }
  1091. state->cyclic_include_hashes.erase(code_hash); // Remove this hash.
  1092. if (!state->disabled) {
  1093. if (state->condition_depth != 0) {
  1094. set_error(RTR("Unmatched conditional statement."), p_tokenizer.line);
  1095. return FAILED;
  1096. }
  1097. expand_output_macros(last_size, p_tokenizer.get_line());
  1098. }
  1099. r_result = vector_to_string(output);
  1100. return OK;
  1101. }
  1102. 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) {
  1103. State pp_state;
  1104. if (!p_filename.is_empty()) {
  1105. pp_state.current_filename = p_filename;
  1106. pp_state.save_regions = r_regions != nullptr;
  1107. }
  1108. Error err = preprocess(&pp_state, p_code, r_result);
  1109. if (err != OK) {
  1110. if (r_error_text) {
  1111. *r_error_text = pp_state.error;
  1112. }
  1113. if (r_error_position) {
  1114. *r_error_position = pp_state.include_positions;
  1115. }
  1116. }
  1117. if (r_regions) {
  1118. *r_regions = pp_state.regions[p_filename];
  1119. }
  1120. if (r_includes) {
  1121. *r_includes = pp_state.shader_includes;
  1122. }
  1123. if (r_completion_defines) {
  1124. for (const KeyValue<String, Define *> &E : state->defines) {
  1125. ScriptLanguage::CodeCompletionOption option(E.key, ScriptLanguage::CODE_COMPLETION_KIND_CONSTANT);
  1126. r_completion_defines->push_back(option);
  1127. }
  1128. }
  1129. if (r_completion_options) {
  1130. switch (pp_state.completion_type) {
  1131. case COMPLETION_TYPE_DIRECTIVE: {
  1132. List<String> options;
  1133. get_keyword_list(&options, true, true);
  1134. for (const String &E : options) {
  1135. ScriptLanguage::CodeCompletionOption option(E, ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT);
  1136. r_completion_options->push_back(option);
  1137. }
  1138. } break;
  1139. case COMPLETION_TYPE_PRAGMA: {
  1140. List<String> options;
  1141. ShaderPreprocessor::get_pragma_list(&options);
  1142. for (const String &E : options) {
  1143. ScriptLanguage::CodeCompletionOption option(E, ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT);
  1144. r_completion_options->push_back(option);
  1145. }
  1146. } break;
  1147. case COMPLETION_TYPE_CONDITION: {
  1148. ScriptLanguage::CodeCompletionOption option("defined", ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT);
  1149. r_completion_options->push_back(option);
  1150. } break;
  1151. case COMPLETION_TYPE_INCLUDE_PATH: {
  1152. if (p_include_completion_func && r_completion_options) {
  1153. p_include_completion_func(r_completion_options);
  1154. }
  1155. } break;
  1156. default: {
  1157. }
  1158. }
  1159. }
  1160. clear_state();
  1161. return err;
  1162. }
  1163. void ShaderPreprocessor::get_keyword_list(List<String> *r_keywords, bool p_include_shader_keywords, bool p_ignore_context_keywords) {
  1164. r_keywords->push_back("define");
  1165. if (!p_ignore_context_keywords) {
  1166. r_keywords->push_back("defined");
  1167. }
  1168. r_keywords->push_back("elif");
  1169. if (p_include_shader_keywords) {
  1170. r_keywords->push_back("else");
  1171. }
  1172. r_keywords->push_back("endif");
  1173. if (p_include_shader_keywords) {
  1174. r_keywords->push_back("if");
  1175. }
  1176. r_keywords->push_back("ifdef");
  1177. r_keywords->push_back("ifndef");
  1178. r_keywords->push_back("include");
  1179. r_keywords->push_back("pragma");
  1180. r_keywords->push_back("undef");
  1181. }
  1182. void ShaderPreprocessor::get_pragma_list(List<String> *r_pragmas) {
  1183. r_pragmas->push_back("disable_preprocessor");
  1184. }
  1185. ShaderPreprocessor::ShaderPreprocessor() {
  1186. }
  1187. ShaderPreprocessor::~ShaderPreprocessor() {
  1188. }