shader_preprocessor.cpp 34 KB

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