shader_preprocessor.cpp 33 KB

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