Blender V5.3
resource_table.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2024 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include "intermediate.hh"
10#include "metadata.hh"
11#include "processor.hh"
12
13#include <ranges>
14#include <string>
15#include <utility>
16#include <vector>
17
18namespace blender::gpu::shader {
19using namespace std;
20using namespace shader::parser;
21using namespace shader::parser::ast;
22using namespace metadata;
23
33void SourceProcessor::lower_srt_accessor_templates(Parser &parser)
34{
35 parser().foreach_token(Struct, [&](Token tok) {
36 Scope body = tok.find_next(lexit::BracketOpen).scope();
37 body.foreach_declaration([&](Scope attributes,
38 Token,
39 Token type,
40 Scope template_scope,
41 Token name,
42 Scope array,
43 Token) {
44 if (attributes[1].str() != "resource_table") {
45 if (type.str() == "srt_t") {
46 report_error(name,
47 "The srt_t<T> template is only to be used with members declared with the "
48 "[[resource_table]] attribute.");
49 }
50 return;
51 }
52
53 if (type.str() != "srt_t") {
54 report_error(type,
55 "Members declared with the [[resource_table]] attribute must wrap their type "
56 "with the srt_t<T> template.");
57 }
58
59 if (array.is_valid()) {
60 report_error(name, "[[resource_table]] members cannot be arrays.");
61 }
62 if (name.prev() == '&') {
63 report_error(name.prev(), "[[resource_table]] members cannot be references.");
64 }
65
66 /* Remove the template but not the wrapped type. */
67 parser.erase(type);
68 if (template_scope.is_valid()) {
69 parser.erase(template_scope.front());
70 parser.erase(template_scope.back());
71 }
72 });
73 });
74 parser.apply_mutations();
75}
76
86void SourceProcessor::lower_srt_accessor_templates_ast(Parser &parser)
87{
88 for (ClassDecl decl : parser.root().descendants_of_type<ClassDecl>()) {
89 for (VarDecl var : decl.body().children_of_type<VarDecl>()) {
90 IdType type = var.type();
91 bool is_resource_table = var.attributes().contains_attr("resource_table");
92 bool is_srt = type.identifier().name().str() == "srt_t";
93 if (!is_srt) {
94 continue;
95 }
96
97 if (!is_resource_table) {
98 report_error(var,
99 "The srt_t<T> template is only to be used with members declared with the "
100 "[[resource_table]] attribute.");
101 continue;
102 }
103
104 for (Declarator decl : var.children_of_type<Declarator>()) {
105 if (decl.is_array()) {
106 report_error(decl, "[[resource_table]] members cannot be arrays.");
107 }
108 if (decl.is_reference()) {
109 report_error(decl, "[[resource_table]] members cannot be references.");
110 }
111 }
112
113 /* Remove the template but not the wrapped type. */
114 parser.erase(type.identifier().name());
115 TemplateParamList list = type.identifier().template_params();
116 if (list.is_valid()) {
117 parser.erase(list.front());
118 parser.erase(list.back());
119 }
120 }
121 }
122
123 parser.apply_mutations();
124}
125
126/* Add `srt_access` around all member access of SRT variables.
127 * Need to run before local reference mutations. */
128void SourceProcessor::lower_srt_member_access(Parser &parser)
129{
130 const string srt_attribute = "resource_table";
131
132 auto memher_access_mutation = [&](Scope attribute, Token type, Token var, Scope body_scope) {
133 if (attribute[2].str() != srt_attribute) {
134 return;
135 }
136
137 const bool is_func_prototype_decl = body_scope.is_invalid();
138 const bool is_local_reference = attribute.scope().type() != ScopeType::FunctionArgs &&
139 attribute.scope().type() != ScopeType::FunctionArg;
140
141 if (is_local_reference || is_func_prototype_decl) {
142 parser.replace(attribute, "");
143 }
144
145 /* Change references to copies to allow placeholder "*_new_()" function result to be passed
146 * as argument. Once these placeholder function are removed, we can pass the value as
147 * reference. */
148 if (!is_local_reference && var.prev() == '&') {
149 parser.erase(var.prev());
150 }
151
152 string srt_type(type.str());
153 string srt_var(var.str());
154
155 body_scope.foreach_match("A.A", [&](const vector<Token> toks) {
156 if (toks[0].str() != srt_var || toks[0].prev() == '.') {
157 return;
158 }
159 parser.replace(
160 toks[0], toks[2], "srt_access(" + srt_type + ", " + string(toks[2].str()) + ")", true);
161 });
162 };
163
164 parser().foreach_scope(ScopeType::FunctionArgs, [&](const Scope fn_args) {
165 /* Parse both function and prototypes. */
166 Scope fn_body = fn_args.next().type() == ScopeType::Function ? fn_args.next() : Scope(parser);
167 /* Function arguments. */
168 fn_args.foreach_match("[[..]]c?A&A", [&](const vector<Token> toks) {
169 memher_access_mutation(toks[0].scope(), toks[8], toks[10], fn_body);
170 });
171 fn_args.foreach_match("[[..]]c?AA", [&](const vector<Token> toks) {
172 if (toks[1].next().str() == srt_attribute) {
173 parser.erase(toks[0].scope());
174 report_error(toks[9], "Shader Resource Table arguments must be references.");
175 }
176 });
177 });
178
179 parser().foreach_scope(ScopeType::Function, [&](const Scope fn_body) {
180 /* Local references. */
181 fn_body.foreach_match("[[..]]c?A&A", [&](const vector<Token> toks) {
182 memher_access_mutation(toks[0].scope(), toks[8], toks[10], toks[10].scope());
183 });
184 /* Local variables. */
185 fn_body.foreach_match("[[..]]c?AA", [&](const vector<Token> toks) {
186 memher_access_mutation(toks[0].scope(), toks[8], toks[9], toks[9].scope());
187 });
188 });
189
190 parser.apply_mutations();
191}
192
193/* Add #ifdef directive around functions using SRT arguments.
194 * Need to run after `lower_entry_points_signature`. */
195void SourceProcessor::lower_srt_arguments(Parser &parser)
196{
197 /* SRT arguments. */
198 parser().foreach_function([&](bool, Token fn_type, Token, Scope fn_args, bool, Scope fn_body) {
199 string condition;
200 fn_args.foreach_match("[[..]]c?A", [&](const vector<Token> &tokens) {
201 if (tokens[1].next().str() != "resource_table") {
202 return;
203 }
204 string srt_cond;
205 tokens[1].scope().foreach_attribute([&](Token attribute_name, Scope attribute_parameters) {
206 if (attribute_name.str() == "condition") {
207 srt_cond = "SRT_CONSTANT_" + string(attribute_parameters.str_exclusive());
208 }
209 });
210
211 condition += " && ";
212 if (!srt_cond.empty()) {
213 /* If condition exists, ensure the function will be available if the condition is false */
214 condition += "(!(" + srt_cond + ") ||";
215 }
216 condition += "defined(CREATE_INFO_" + string(tokens[8].str()) + ")";
217 if (!srt_cond.empty()) {
218 condition += ")";
219 }
220 parser.replace(tokens[0].scope(), "");
221 });
222
223 if (!condition.empty()) {
224 /* Take attribute into account. */
225 Token first_tok = fn_type.prev() == ']' ? fn_type.prev().scope().front() : fn_type;
226 parser.insert_directive(first_tok.prev(), "#if " + condition.substr(4));
227 parser.insert_directive(fn_body.back(), "#endif");
228 }
229 });
230
231 parser.apply_mutations();
232}
233
234/* Add ifdefs guards around scopes using resource accessors. */
235void SourceProcessor::lower_resource_access_functions(Parser &parser)
236{
237 /* Legacy access macros. */
238 parser().foreach_function([&](bool, Token fn_type, Token, Scope, bool, Scope fn_body) {
239 fn_body.foreach_match("A(", [&](const vector<Token> &tokens) {
240 string_view func_name = tokens[0].str();
241 if (func_name != "specialization_constant_get" && func_name != "shared_variable_get" &&
242 func_name != "push_constant_get" && func_name != "interface_get" &&
243 func_name != "resource_table_get" && func_name != "attribute_get" &&
244 func_name != "buffer_get" && func_name != "sampler_get" && func_name != "image_get")
245 {
246 return;
247 }
248
249 if (tokens[1].next() != Word) {
250 report_error(tokens[1].next(), "Expecting symbol name");
251 return;
252 }
253
254 string info_name(tokens[1].next().str());
255 Scope scope = tokens[0].scope();
256 /* We can be in expression scope. Take parent scope until we find a local scope. */
257 while (scope.type() != ScopeType::Function && scope.type() != ScopeType::Local) {
258 scope = scope.scope();
259 }
260
261 string condition = "defined(CREATE_INFO_" + info_name + ")";
262
263 if (scope.type() == ScopeType::Function) {
264 guarded_scope_mutation(parser, scope, condition, fn_type);
265 }
266 else {
267 guarded_scope_mutation(parser, scope, condition, Token(parser));
268 }
269 });
270 });
271
272 parser.apply_mutations();
273}
274
291void SourceProcessor::lower_using(Parser &parser)
292{
293 parser().foreach_match("un", [&](const vector<Token> &tokens) {
294 report_error(tokens[0],
295 "Unsupported `using namespace`. "
296 "Add individual `using` directives for each needed symbol.");
297 });
298
299 auto process_using = [&](const Token &using_tok,
300 const Token &from,
301 const Token &to_start,
302 const Token &to_end,
303 const Token &end_tok) {
304 string to = parser.substr_range_inclusive(to_start, to_end);
305 string namespace_prefix = parser.substr_range_inclusive(to_start, to_end.prev().prev().prev());
306 Scope scope = from.scope();
307
308 /* Using the keyword in global or at namespace scope. */
309 if (scope.type() == ScopeType::Global) {
310 report_error(using_tok, "The `using` keyword is not allowed in global scope.");
311 return;
312 }
313 if (scope.type() == ScopeType::Namespace) {
314 /* Ensure we are bringing symbols from the same namespace.
315 * Otherwise we can have different shadowing outcome between shader and C++. */
316 string namespace_name = scope.front().prev().full_symbol_name();
317 if (namespace_name != namespace_prefix) {
318 report_error(
319 using_tok,
320 "The `using` keyword is only allowed in namespace scope to make visible symbols "
321 "from the same namespace declared in another scope, potentially from another "
322 "file.");
323 return;
324 }
325 }
326
327 /* Assignments do not allow to alias functions symbols. */
328 const bool use_alias = from.str() != to_end.str();
329 const bool replace_fn = !use_alias;
330 /* IMPORTANT: If `replace_fn` is true, this can replace any symbol type if there are functions
331 * and types with the same name. We could support being more explicit about the type of
332 * symbol to replace using an optional attribute [[gpu::using_function]]. */
333
334 /* Replace all occurrences of the non-namespace specified symbol. */
335 scope.foreach_token(Word, [&](const Token &token) {
336 /* Do not replace symbols before the using statement. */
337 if (token.index_ <= to_end.index_) {
338 return;
339 }
340 /* Reject symbols that contain the target symbol name. */
341 if (token.prev() == ':') {
342 return;
343 }
344 if (!replace_fn && token.next() == '(') {
345 return;
346 }
347 if (token.str() != from.str()) {
348 return;
349 }
350 parser.replace(token, to, true);
351 });
352
353 parser.erase(using_tok, end_tok);
354 };
355
356 parser().foreach_match("uA::A", [&](const vector<Token> &tokens) {
357 Token end = tokens.back().find_next(SemiColon);
358 process_using(tokens[0], end.prev(), tokens[1], end.prev(), end);
359 });
360
361 parser().foreach_match("uA=A::A", [&](const vector<Token> &tokens) {
362 Token end = tokens.back().find_next(SemiColon);
363 process_using(tokens[0], tokens[1], tokens[3], end.prev(), end);
364 });
365
366 parser.apply_mutations();
367
368 /* Verify all using were processed. */
369 parser().foreach_token(Using, [&](const Token &token) {
370 report_error(token, "Unsupported `using` keyword usage.");
371 });
372}
373
374/* Parse SRT and interfaces, remove their attributes and create init function for SRT structs. */
375void SourceProcessor::lower_resource_table(Parser &parser)
376{
377 enum class SrtType {
378 undefined,
379 none,
381 vertex_input,
382 vertex_output,
383 fragment_output,
384 fragment_input,
385 };
386
387 auto parse_resource = [&](Scope attributes, Token type, Token name, Scope array) {
388 /* FIXME(fclem): This is a hotfix to support multi dimensional array.
389 * Ideally, array should already contain all dimensions */
390 Scope array_end = array;
391 while (array_end.next().type() == ScopeType::Subscript) {
392 array_end = array_end.next();
393 }
394 string_view array_str;
395 if (array.is_valid()) {
396 array_str = parser.substr(array.front(), array_end.back(), true);
397 }
398
399 metadata::ParsedResource resource{
400 type.line_number(), string(type.str()), string(name.str()), string(array_str)};
401 attributes.foreach_scope(ScopeType::Attribute, [&](const Scope &attribute) {
402 string_view type = attribute[0].str();
403 if (type == "sampler") {
404 resource.res_type = type;
405 resource.res_slot = attribute[2].str();
406 }
407 else if (type == "image") {
408 resource.res_type = type;
409 resource.res_slot = attribute[2].str();
410 resource.res_qualifier = attribute[4].str();
411 resource.res_format = attribute[6].str();
412 }
413 else if (type == "uniform") {
414 resource.res_type = type;
415 resource.res_slot = attribute[2].str();
416 }
417 else if (type == "storage") {
418 resource.res_type = type;
419 resource.res_slot = attribute[2].str();
420 resource.res_qualifier = attribute[4].str();
421 }
422 else if (type == "acceleration_structure") {
423 resource.res_type = type;
424 resource.res_slot = attribute[2].str();
425 resource.res_qualifier = attribute[4].str();
426 }
427 else if (type == "shared") {
428 resource.res_type = type;
429 }
430 else if (type == "push_constant") {
431 resource.res_type = type;
432 }
433 else if (type == "compilation_constant") {
434 resource.res_type = type;
435 }
436 else if (type == "specialization_constant") {
437 resource.res_type = type;
438 resource.res_value = attribute[1].scope().str_exclusive();
439 }
440 else if (type == "condition") {
441 attribute[1].scope().foreach_token(Word, [&](const Token tok) {
442 resource.res_condition += "int " + string(tok.str()) + " = ";
443 resource.res_condition += "ShaderCreateInfo::find_constant(constants, \"" +
444 string(tok.str()) + "\"); ";
445 });
446 resource.res_condition += "return " + string(attribute[1].scope().str()) + ";";
447 }
448 else if (type == "frequency") {
449 resource.res_frequency = attribute[2].str();
450 }
451 else if (type == "resource_table") {
452 resource.res_type = type;
453 }
454 else if (type == "legacy_info") {
455 resource.res_type = type;
456 }
457 else if (type == "legacy_iface") {
458 resource.res_type = type;
459 }
460 else {
461 report_error(attribute[0], "Invalid attribute in resource table");
462 }
463 });
464 return resource;
465 };
466
467 auto parse_vertex_input = [&](Scope attributes, Token type, Token name, Scope array) {
468 if (array.is_valid()) {
469 report_error(array[0], "Array are not supported as vertex attributes");
470 }
471
472 metadata::ParsedVertInput vert_in{type.line_number(), string(type.str()), string(name.str())};
473
474 if (vert_in.var_type == "float3x3" || vert_in.var_type == "float2x2" ||
475 vert_in.var_type == "float4x4" || vert_in.var_type == "float3x4")
476 {
477 report_error(name, "Matrices are not supported as vertex attributes");
478 }
479
480 attributes.foreach_scope(ScopeType::Attribute, [&](const Scope &attribute) {
481 string_view type = attribute[0].str();
482 if (type == "attribute") {
483 vert_in.slot = attribute[2].str();
484 }
485 else if (type == "condition") {
486 attribute[1].scope().foreach_token(Word, [&](const Token tok) {
487 vert_in.res_condition += "int " + string(tok.str()) + " = ";
488 vert_in.res_condition += "ShaderCreateInfo::find_constant(constants, \"" +
489 string(tok.str()) + "\"); ";
490 });
491 vert_in.res_condition += "return " + string(attribute[1].scope().str()) + ";";
492 }
493 else {
494 report_error(attribute[0], "Invalid attribute in vertex input interface");
495 }
496 });
497 return vert_in;
498 };
499
500 auto parse_vertex_output =
501 [&](Token struct_name, Scope attributes, Token type, Token name, Scope array) {
502 if (array.is_valid()) {
503 report_error(array[0], "Array are not supported in stage interface");
504 }
505
506 Token interpolation_mode = attributes[1];
507
508 metadata::ParsedAttribute attr{type.line_number(),
509 string(type.str()),
510 string(struct_name.str()) + "_" + string(name.str()),
511 string(interpolation_mode.str())};
512
513 if (attr.var_type == "float3x3" || attr.var_type == "float2x2" ||
514 attr.var_type == "float4x4" || attr.var_type == "float3x4")
515 {
516 report_error(name, "Matrices are not supported in stage interface");
517 }
518
519 if (attr.interpolation_mode != "smooth" && attr.interpolation_mode != "flat" &&
520 attr.interpolation_mode != "no_perspective")
521 {
522 report_error(attributes[0], "Invalid attribute in shader stage interface");
523 }
524 return attr;
525 };
526
527 auto parse_fragment_output =
528 [&](Token struct_name, Scope attributes, Token tok_type, Token name, Scope) {
529 metadata::ParsedFragOuput frag_out{tok_type.line_number(),
530 string(tok_type.str()),
531 string(struct_name.str()) + "_" + string(name.str())};
532
533 attributes.foreach_scope(ScopeType::Attribute, [&](const Scope &attribute) {
534 string_view type = attribute[0].str();
535 if (type == "frag_color") {
536 frag_out.slot = attribute[2].str();
537 }
538 else if (type == "raster_order_group") {
539 frag_out.raster_order_group = attribute[2].str();
540 }
541 else if (type == "index") {
542 frag_out.dual_source = attribute[2].str();
543 }
544 else {
545 report_error(attributes[0], "Invalid attribute in fragment output interface");
546 }
547 });
548 return frag_out;
549 };
550
551 auto parse_fragment_input =
552 [&](Token struct_name, Scope attributes, Token tok_type, Token name, Scope) {
553 metadata::ParsedFragInput frag_in{tok_type.line_number(),
554 string(tok_type.str()),
555 string(struct_name.str()) + "_" + string(name.str())};
556
557 attributes.foreach_scope(ScopeType::Attribute, [&](const Scope &attribute) {
558 string_view type = attribute[0].str();
559 if (type == "subpass_input") {
560 frag_in.slot = attribute[2].str();
561 frag_in.image_type = attribute[4].str();
562 }
563 else if (type == "raster_order_group") {
564 frag_in.raster_order_group = attribute[2].str();
565 }
566 else {
567 report_error(attributes[0], "Invalid attribute in fragment output interface");
568 }
569 });
570 return frag_in;
571 };
572
573 auto is_resource_table_attribute = [](Token attr) {
574 string_view type = attr.str();
575 return (type == "sampler" || type == "image" || type == "uniform" || type == "storage" ||
576 type == "acceleration_structure" || type == "shared" || type == "push_constant" ||
577 type == "compilation_constant" || type == "specialization_constant" ||
578 type == "legacy_info" || type == "legacy_iface" || type == "resource_table");
579 };
580 auto is_vertex_input_attribute = [](Token attr) {
581 string_view type = attr.str();
582 return (type == "attribute");
583 };
584 auto is_vertex_output_attribute = [](Token attr) {
585 string_view type = attr.str();
586 return (type == "flat" || type == "smooth" || type == "no_perspective");
587 };
588 auto is_fragment_output_attribute = [](Token attr) {
589 string_view type = attr.str();
590 return (type == "frag_color" || type == "frag_depth" || type == "frag_stencil_ref");
591 };
592 auto is_fragment_input_attribute = [](Token attr) {
593 string_view type = attr.str();
594 return (type == "subpass_input");
595 };
596
597 parser().foreach_struct([&](Token struct_tok, Scope, Token struct_name, Scope body) {
598 SrtType srt_type = SrtType::undefined;
599 bool has_srt_members = false;
600
601 metadata::ResourceTable srt;
602 metadata::VertexInputs vertex_in;
603 metadata::StageInterface vertex_out;
604 metadata::FragmentOutputs fragment_out;
605 metadata::FragmentInputs fragment_in;
606 srt.name = struct_name.str();
607 vertex_in.name = struct_name.str();
608 vertex_out.name = struct_name.str();
609 fragment_out.name = struct_name.str();
610 fragment_in.name = struct_name.str();
611
612 body.foreach_declaration([&](Scope attributes,
613 Token const_tok,
614 Token type,
615 Scope /*template_scope*/, /* TODO */
616 Token name,
617 Scope array,
618 Token decl_end) {
619 SrtType decl_type = SrtType::undefined;
620 if (attributes.is_invalid()) {
621 decl_type = SrtType::none;
622 }
623 else if (is_resource_table_attribute(attributes[1])) {
624 decl_type = SrtType::resource_table;
625 }
626 else if (is_vertex_input_attribute(attributes[1])) {
627 decl_type = SrtType::vertex_input;
628 }
629 else if (is_vertex_output_attribute(attributes[1])) {
630 decl_type = SrtType::vertex_output;
631 }
632 else if (is_fragment_output_attribute(attributes[1])) {
633 decl_type = SrtType::fragment_output;
634 }
635 else if (is_fragment_input_attribute(attributes[1])) {
636 decl_type = SrtType::fragment_input;
637 }
638 else {
639 return;
640 }
641
642 if (srt_type == SrtType::undefined) {
643 srt_type = decl_type;
644 }
645 else if (srt_type != decl_type) {
646 switch (srt_type) {
647 case SrtType::resource_table:
648 report_error(struct_name, "Structure expected to contain resources...");
649 break;
650 case SrtType::vertex_input:
651 report_error(struct_name, "Structure expected to contain vertex inputs...");
652 break;
653 case SrtType::vertex_output:
654 report_error(struct_name, "Structure expected to contain vertex outputs...");
655 break;
656 case SrtType::fragment_output:
657 report_error(struct_name, "Structure expected to contain fragment outputs...");
658 break;
659 case SrtType::fragment_input:
660 report_error(struct_name, "Structure expected to contain fragment inputs...");
661 break;
662 case SrtType::none:
663 report_error(struct_name, "Structure expected to contain plain data...");
664 break;
665 case SrtType::undefined:
666 break;
667 }
668
669 switch (decl_type) {
670 case SrtType::resource_table:
671 report_error(attributes[1], "...but member declared as resource.");
672 break;
673 case SrtType::vertex_input:
674 report_error(attributes[1], "...but member declared as vertex input.");
675 break;
676 case SrtType::vertex_output:
677 report_error(attributes[1], "...but member declared as vertex output.");
678 break;
679 case SrtType::fragment_output:
680 report_error(attributes[1], "...but member declared as fragment output.");
681 break;
682 case SrtType::fragment_input:
683 report_error(attributes[1], "...but member declared as fragment input.");
684 break;
685 case SrtType::none:
686 report_error(name, "...but member declared as plain data.");
687 break;
688 case SrtType::undefined:
689 break;
690 }
691 }
692
693 switch (decl_type) {
694 case SrtType::resource_table:
695 srt.emplace_back(parse_resource(attributes, type, name, array));
696 if (attributes[1].str() == "resource_table") {
697 has_srt_members = true;
698 parser.erase(attributes.scope());
699 parser.erase(const_tok);
700 }
701 else {
702 parser.erase(attributes.front().line_start(), decl_end.line_end());
703 }
704 break;
705 case SrtType::vertex_input:
706 vertex_in.emplace_back(parse_vertex_input(attributes, type, name, array));
707 parser.erase(attributes.scope());
708 break;
709 case SrtType::vertex_output:
710 vertex_out.emplace_back(parse_vertex_output(struct_name, attributes, type, name, array));
711 parser.erase(attributes.scope());
712 break;
713 case SrtType::fragment_output:
714 fragment_out.emplace_back(
715 parse_fragment_output(struct_name, attributes, type, name, array));
716 parser.erase(attributes.scope());
717 break;
718 case SrtType::fragment_input:
719 fragment_in.emplace_back(
720 parse_fragment_input(struct_name, attributes, type, name, array));
721 parser.erase(attributes.scope());
722 break;
723 case SrtType::undefined:
724 case SrtType::none:
725 break;
726 }
727 });
728
729 switch (srt_type) {
730 case SrtType::resource_table:
731 metadata_.resource_tables.emplace_back(srt);
732 break;
733 case SrtType::vertex_input:
734 metadata_.vertex_inputs.emplace_back(vertex_in);
735 break;
736 case SrtType::vertex_output:
737 metadata_.stage_interfaces.emplace_back(vertex_out);
738 break;
739 case SrtType::fragment_output:
740 metadata_.fragment_outputs.emplace_back(fragment_out);
741 break;
742 case SrtType::fragment_input:
743 metadata_.fragment_inputs.emplace_back(fragment_in);
744 break;
745 case SrtType::undefined:
746 case SrtType::none:
747 break;
748 }
749
750 Token end_of_srt = body.back().prev();
751
752 if (srt_type == SrtType::resource_table) {
753 /* Add static constructor.
754 * These are only to avoid warnings on certain backend compilers. */
755 string ctor;
756 ctor += "\nstatic " + srt.name + " new_()\n";
757 ctor += "{\n";
758 ctor += " " + srt.name + " result;\n";
759 if (has_srt_members == false) {
760 ctor += " result._pad = 0;\n";
761 }
762 for (const auto &member : srt) {
763 if (member.res_type == "resource_table") {
764 ctor += " result." + member.var_name + " = " + member.var_type + "::new_();\n";
765 }
766 }
767 ctor += " return result;\n";
768 /* Avoid messing up the line count and keep empty struct empty. */
769 ctor += "#line " + to_string(end_of_srt.line_number()) + "\n";
770 ctor += "}\n";
771 parser.insert_after(end_of_srt, ctor);
772
773 {
774 string access_macros;
775 for (const auto &member : srt) {
776 if (member.res_type == "resource_table") {
777 access_macros += "#define access_" + srt.name + "_" + member.var_name + "() ";
778 access_macros += member.var_type + "_ctor_()\n";
779 }
780 else {
781 access_macros += "#define access_" + srt.name + "_" + member.var_name + "() ";
782 access_macros += member.var_name + "\n";
783 }
784 }
785 parser.insert_before(struct_tok, access_macros);
786 parser.insert_before(struct_tok, get_create_info_placeholder(srt.name));
787
788 parser.insert_before(struct_tok, "\n");
789 parser.insert_line_number(struct_tok.str_index_start() - 1, struct_tok.line_number());
790 }
791
792 /* Insert attribute so that method mutations know that this struct is an SRT. */
793 if (parser.language == Language::BSL) {
794 parser.insert_after(struct_tok, "[[resource_table]] ");
795 }
796 else {
797 parser.insert_before(struct_tok, "[[resource_table]] ");
798 }
799 }
800 });
801
802 parser.parse(error_handler);
803}
804
805void SourceProcessor::lower_resource_macro_placeholder_ast(Parser &parser)
806{
807 auto split_into_pairs = [](const string &str) {
808 vector<pair<string, string>> result;
809 /* Split by spaces. */
810 auto words_view = str | std::views::split(' ');
811
812 string first_of_pair;
813 for (auto &&word_range : words_view) {
814 string word(word_range.begin(), word_range.end());
815 if (first_of_pair.empty()) {
816 first_of_pair = std::move(word);
817 }
818 else {
819 result.emplace_back(std::move(first_of_pair), std::move(word));
820 }
821 }
822 return result;
823 };
824
825 for (Preprocessor directive : parser.root().descendants_of_type<Preprocessor>()) {
826 string_view dir_str = directive.str();
827 if (dir_str.starts_with("#pragma resource_access ")) {
828 auto pairs = split_into_pairs(string(dir_str));
829 for (auto pair : pairs) {
830 if (pair.first != "#pragma") {
831 parser.insert_before(directive.front(),
832 "#define " + pair.first + " " + pair.second + "\n");
833 }
834 }
835 parser.erase(directive);
836 }
837 else if (dir_str.starts_with("#pragma resource_defines ")) {
838 string_view str_name = directive.back().str();
839 parser.replace(directive, get_create_info_placeholder(string(str_name)));
840 }
841 }
842}
843
844} // namespace blender::gpu::shader
static std::string get_create_info_placeholder(const std::string &name)
Definition processor.cc:660
static void guarded_scope_mutation(Parser &parser, Scope scope, const std::string &condition, Token fn_type)
#define str(s)
#define resource_table
#define attribute(slot)
#define condition(cond)
const char * to_string(ShaderStage stage)
Definition mtl_shader.mm:52
SymEdge< T > * prev(const SymEdge< T > *se)
@ BracketOpen
Definition types.hh:55
@ Struct
Definition types.hh:117
@ Using
Definition types.hh:121
@ SemiColon
Definition types.hh:62
@ Word
Definition types.hh:43
void foreach_declaration(Callback callback) const
Definition scope.hh:467
std::string_view str() const
Definition scope.hh:194
void foreach_scope(ScopeType type, CallbackFn callback) const
Definition scope.hh:339
Token prev(int i=1) const
Definition lexit.hh:376
Token(const TokenBuffer *buf, int32_t index)
Definition lexit.hh:337