91 :
str((var->is_constexpr ? var->value_str() : var->identifier) + trivia),
117 :
public PrattParser<CodegenExpressionParser, CodegenResult, ast::Node> {
126 optional<SourceLocation> poi;
131 : ctx(ctx), scope(scope), node(start_node)
140 if (!node.is_valid()) {
141 return {node, ctx.table.err_cls};
154 return constructor(t);
156 return function(t, scope);
160 return {t, ctx.table.err_cls};
162 return {t, ctx.table.err_cls};
167 return {t, ctx.table.get_literal_type(t.
str())};
172 return {t, ctx.table.str_cls};
186 switch (right.
type()) {
204 return {t, ctx.table.err_cls};
218 left.
str += string(front) + param.
str + string(back);
230 left.
str += string(front) + param.
str + string(back);
235 return {t, ctx.table.err_cls};
241 return {t, ctx.table.err_cls};
250 ClassId type = unary_prefix_operator_return_type(op_type, rhs.
type);
257 return {string(t.
str_full()) + rhs.
str, ctx.table.to_class(type)};
265 ClassId type = unary_suffix_operator_return_type(lhs.
type, op_type);
272 return {lhs.
str + string(t.
str_full()), ctx.table.to_class(type)};
289 ClassId type = binary_operator_return_type(lhs.
type, op_type, rhs.
type);
295 ctx.table.to_class(type)};
301 const string op_name = ctx.table.binary_type_to_id.find(op_type)->second;
302 return {op_name +
'(' + lhs.
str +
',' + rhs.
str +
')', type};
305 return {lhs.
str + string(t.
str_full()) + rhs.
str, ctx.table.to_class(type)};
324 return node.is_valid() ? node.front().type() :
Invalid;
347 case ErrorType::ExpectedParenthesis:
350 case ErrorType::ExpectedColon:
353 case ErrorType::InvalidOperator:
356 case ErrorType::InvalidExpression:
360 return {node, ctx.table.err_cls};
374 CodegenResult variable(
IdQualified id,
const SymbolScope &symbol_scope)
377 string whitespace = trivia(
id);
379 SymbolVariable *var = symbol_scope.lookup_variable(ctx.
table,
id);
382 return {var, whitespace};
385 if (var->is_constexpr) {
386 return {var, whitespace};
389 if (var->condition.is_valid()) {
390 ctx.check_condition(
id, var->condition);
393 if (var->type->is_srt()) {
394 bool followed_by_dot =
id.back().next() ==
'.';
395 bool followed_by_member_call =
id.parent().next().next() == NodeType::FuncCall;
396 if (followed_by_dot && !followed_by_member_call) {
398 return {as_whitespace(
id.str_full()), var->type};
401 return {var->type->identifier +
"_ctor_()" + whitespace, var->type};
404 if (var->reference_value.is_valid()) {
405 return ctx.expr(var->reference_value, scope);
408 bool preceded_by_dot =
id.front().prev() ==
'.';
409 if (!var->is_static && !preceded_by_dot && var->parent->as_class() !=
nullptr) {
410 return {
"this_." + var->identifier + whitespace, var->type, var->array_dimensions};
412 return {var, whitespace};
415 CodegenResult function(
const ast::FuncCall &call,
const SymbolScope &symbol_scope)
423 SourceLocation loc = (&symbol_scope != &scope) ? poi.value_or(
id.front()) :
id.
front();
425 SymbolFunction *
sym = ctx.id_func_resolved_lookup(
426 id, call.
parameters(), symbol_scope, scope, loc);
428 if (sym ==
nullptr ||
sym->is_error) {
430 return {
"", ctx.table.err_cls};
433 if (
sym->is_inline) {
438 std::string params_str;
440 params_str +=
"this_";
448 params_str += ctx.expr(param, scope).str;
449 params_str += ctx.opt_str(param.back().next(),
Comma);
454 for (; param_count <
sym->arg_defaults.size(); ++param_count) {
455 if (
sym->arg_defaults[param_count].is_valid()) {
456 if (param_count != 0) {
460 params_str += ctx.expr(
sym->arg_defaults[param_count], *sym).str;
470 return {
sym->identifier + trivia(
id) + params_str,
sym->return_type};
527 local_scope(
node, symbol);
532 static string trivia(
Token t)
534 string_view no_ws = t.
str();
540 return trivia(
node.back());
543 static string as_whitespace(string_view
str)
545 size_t lines = count(
str.begin(),
str.end(),
'\n');
546 size_t spaces =
str.find_last_of(
"\n");
547 if (spaces != string::npos) {
548 spaces =
str.length() - (spaces + 1);
551 spaces =
str.length();
553 return string(lines,
'\n') + string(spaces,
' ');
556 void skip_node(Node
node)
558 if (
node.is_valid()) {
559 const TokenBuffer *buf =
node.front().buf_;
567 template<
typename... Args>
bool skip_if(Args... expected)
587 void jump_to(
Token tok)
590 builder.
ss << string(tok.char_number(),
' ');
595 template<
typename... Args>
bool match_if(Args... expected)
604 void local_scope(LocalScope
node, SymbolScope &symbol)
610 bool has_bracket =
false;
611 if (symbol.parent !=
nullptr) {
616 has_bracket = match_if(
'{');
622 string cond = !symbol.as_function() ? condition(&symbol) :
"";
624 builder.
ss << string(
"\n#if ") + cond +
"\n";
628 if (
node.child_first().is_valid()) {
629 jump_to(
node.child_first().front());
632 int local_scope_id = 0;
633 for (Node
node :
node.children_range()) {
634 switch (
node.type()) {
635 case NodeType::Preprocessor:
636 jump_to(
node.front());
639 case NodeType::Namespace:
642 case NodeType::VarDecl:
645 case NodeType::ClassDecl:
648 case NodeType::FuncDecl:
651 case NodeType::FuncForwardDecl:
654 case NodeType::TemplateDecl:
657 case NodeType::TemplateInst:
660 case NodeType::TemplateSpec:
663 case NodeType::UsingStmt:
666 case NodeType::ForLoop:
667 for_loop(
node, *symbol.child_scope(local_scope_id++));
669 case NodeType::WhileLoop:
670 while_loop(
node, *symbol.child_scope(local_scope_id++));
672 case NodeType::DoWhileLoop:
673 do_while_loop(
node, *symbol.child_scope(local_scope_id++));
675 case NodeType::SwitchStmt:
676 switch_statement(
node, symbol, local_scope_id);
678 case NodeType::ReturnStmt:
679 return_statement(
node, symbol);
681 case NodeType::StructuredBinding:
682 structured_binding(
node, symbol);
684 case NodeType::IfStmt:
685 if (
Condition(
node.child_first()).attributes().contains_attr(
"static_branch")) {
686 static_if_statement(
node, symbol, local_scope_id);
689 if_statement(
node, symbol, local_scope_id);
692 case NodeType::ElseIfStmt:
693 case NodeType::ElseStmt:
696 case NodeType::LocalStmt:
697 local_statement(
node, symbol);
699 case NodeType::LocalScope:
700 local_scope(
LocalScope(
node), *symbol.child_scope(local_scope_id++));
702 case NodeType::PipelineDecl:
703 pipeline_decl(
node, symbol);
715 if (symbol.parent !=
nullptr) {
716 jump_to(
node.back());
720 else if (has_bracket) {
726 void pipeline_decl(PipelineDecl stmt, SymbolScope &scope)
730 const bool is_graphic = stmt.
type().
str() ==
"PipelineGraphic";
734 jump_to(stmt.
front());
740 Expr constants_init = Node{};
775 constants_init = frag_fn.
next();
794 constants_init = comp_fn.
next();
798 if (Constructor ctor(constants_init.
child_first()); ctor.is_valid()) {
803 if (list.back().next() ==
',') {
810 constants_init = constants_init.
next();
818 void return_statement(ReturnStmt stmt, SymbolScope &scope)
820 if (SymbolFunction *fn = scope.parent_function(); fn) {
822 if (
auto [r_fn, call] = get_inlined_function(stmt.
expression(), scope); r_fn) {
823 ret_val = inline_function(r_fn, call, scope);
825 jump_to(stmt.
front());
836 if (!ret_val.empty()) {
840 builder.
ss << initializer_list(list, scope, fn->return_type).str;
857 void structured_binding(StructuredBinding decl, SymbolScope &scope)
859 SymbolVariable *tmp_var = scope.lookup_variable(decl.
tmp_id());
866 int pad = assign_front.char_number() - decl_front.char_number();
870 string decl_str = tmp_var->type->identifier +
" " + tmp_var->identifier;
872 builder.
ss << decl_str + string(
max(0,
pad -
int(decl_str.size())),
' ');
875 assignment(assign, scope, tmp_var);
879 void switch_statement(SwitchStmt stmt, SymbolScope &scope,
int &local_scope_id)
882 condition(stmt.
condition(), scope,
false,
false);
886 switch (
node.type()) {
887 case NodeType::Preprocessor:
890 case NodeType::SwitchCase: {
892 jump_to(switch_case.front());
894 if (!switch_case.is_default_case()) {
895 Node val = switch_case.value();
896 if (val.
type() == NodeType::IdQualified) {
897 id_var_resolved(val, scope);
905 local_scope(switch_case.body(), *scope.child_scope(local_scope_id++));
908 case NodeType::Condition:
914 jump_to(stmt.
back());
918 void loop_unroll(ForLoop stmt, SymbolScope &scope)
941 SymbolClass *cls = var->
type;
953 if (!
result.is_constexpr()) {
957 ConstexprValue val =
result.value;
960 if (
node.type() == NodeType::Op &&
node.front() ==
',') {
969 var->is_constexpr =
true;
973 for (
int i = 0;; i++) {
975 if (!
result.is_constexpr()) {
980 if (
result.value.comp_as<
int>(0) == 0) {
990 local_scope(stmt.
body(), scope);
993 var->value = eval_constexpr_with_side_effects(var, end_expr, scope);
1000 var->is_constexpr =
false;
1005 ConstexprValue eval_constexpr_with_side_effects(SymbolVariable *var,
1009 if (expr.child_count() == 2) {
1013 LocalVar local_var = expr.child_first();
1014 if (expr.child_last().type() == NodeType::Op) {
1018 else if (expr.child_first().type() == NodeType::Op) {
1031 return --var->value;
1033 return ++var->value;
1048 Node op = local_var.
next();
1049 if (op.
type() == NodeType::Op) {
1050 Node
node = op.next();
1053 if (!
result.is_constexpr()) {
1061# pragma warning(push)
1062# pragma warning(disable : 4805)
1066 switch (op.front().
type()) {
1068 return var->value =
result.value;
1070 return var->value +=
result.value;
1072 return var->value -=
result.value;
1074 return var->value *=
result.value;
1080 return var->value /=
result.value;
1085# pragma warning(pop)
1094 void for_loop(ForLoop stmt, SymbolScope &scope)
1097 loop_unroll(stmt, scope);
1101 condition(stmt.
condition(), scope,
true,
true);
1102 local_scope(stmt.
body(), scope);
1105 void while_loop(WhileLoop stmt, SymbolScope &scope)
1108 condition(stmt.
condition(), scope,
false,
true);
1109 local_scope(stmt.
body(), scope);
1112 void do_while_loop(DoWhileLoop stmt, SymbolScope &scope)
1115 local_scope(stmt.
body(), scope);
1117 condition(stmt.
condition(), scope,
false,
true);
1121 void local_statement(LocalStmt stmt, SymbolScope &scope)
1125 if (
auto [fn, call] = get_inlined_function(stmt.
expr(), scope); fn) {
1126 inline_function(fn, call, scope);
1138 SymbolScope *
sym = &scope;
1142 skip_if(TokenType::Namespace);
1144 local_scope(ns.
body(), *sym);
1147 void enum_decl(ClassDecl decl, SymbolScope &scope)
1150 SymbolScope *body_scope = &scope;
1152 if (
id.is_valid()) {
1153 auto it = scope.scopes.find(
string(
id.
str()));
1154 if (it == scope.scopes.end()) {
1158 body_scope = it->second;
1160 SymbolClass *enum_cls =
id.
is_valid() ? body_scope->as_class() :
nullptr;
1165 if (enum_cls &&
id.is_valid()) {
1167 builder.
ss <<
"\n#define " << enum_cls->identifier <<
" " << type.
str() <<
"\n";
1170 jump_to(decl.
front());
1175 string type_str = string(
"static constexpr ") + string(type.
str());
1181 SymbolVariable *var = id_var_decl_resolved(val.identifier(), *body_scope);
1182 builder <<
" = " + var->value_str();
1187 void class_decl(ClassDecl decl,
1191 SymbolClass *inst_cls =
nullptr)
1194 enum_decl(decl, scope);
1198 SymbolClass *cls_ptr = inst_cls;
1204 cls_ptr = scope.lookup_class(
"a" +
to_string(nested_id));
1207 SymbolClass &cls = *cls_ptr;
1219 class_decl(decl, cls, class_id);
1225 generate_srt_placeholder_macros(cls);
1226 lint_compilation_constant_redefinition(cls);
1231 if (decl.
type().is_static()) {
1232 var_decl(decl, cls);
1237 jump_to(decl.
front());
1244 if (cls.is_anonymous) {
1255 union_members_decl(cls);
1258 class_members_decl(decl, cls);
1261 jump_to(body.
back());
1266 builder.
ss << class_default_constructor(decl, cls) +
"\n";
1273 for (SymbolVariable *var : cls.non_static_variables_in_declaration_order()) {
1274 builder.
ss << union_getter(cls, *var) +
"\n";
1275 builder.
ss << union_setter(cls, *var) +
"\n";
1284 func_forward_decl(decl, cls);
1290 func_decl(decl, cls);
1295 void class_members_decl(ClassDecl decl, SymbolClass &cls)
1299 int member_count = 0;
1302 switch (
node.type()) {
1303 case NodeType::VarDecl: {
1306 member_count += var_decl(decl, cls);
1310 case NodeType::ClassDecl: {
1314 jump_to(decl.
front());
1316 id_type_resolved(
id, cls);
1328 if (member_count == 0) {
1334 parse_class_metadata(cls, body);
1338 void lint_compilation_constant_redefinition(SymbolClass &cls)
1340 vector<const SymbolVariable *> compilation_constants;
1342 vector<const SymbolClass *> visited_srt;
1344 auto check_class = [&](
auto &self, SymbolClass *cls) {
1345 if (std::ranges::find(visited_srt, cls) != visited_srt.end()) {
1348 visited_srt.emplace_back(cls);
1350 for (
const auto &[k, v] : cls->variables) {
1351 const SymbolVariable &member = *
v.second;
1352 if (member.is_compilation_const) {
1354 for (
const SymbolVariable *other : compilation_constants) {
1355 if (other->original == member.original) {
1360 compilation_constants.emplace_back(&member);
1364 self(self, member.type);
1369 check_class(check_class, &cls);
1372 void generate_srt_placeholder_macros(SymbolClass &cls)
1374 string access_macros =
"#pragma resource_access ";
1375 for (
const auto &[k, v] : cls.variables) {
1376 const SymbolVariable &member = *
v.second;
1377 if (member.type->is_srt()) {
1378 access_macros +=
" access_" + cls.identifier +
"_" + member.identifier +
"()";
1379 access_macros +=
" " + member.type->identifier +
"_ctor_()";
1382 access_macros +=
" access_" + cls.identifier +
"_" + member.identifier +
"()";
1383 access_macros +=
" " + member.identifier +
"";
1387 builder.
ss <<
"\n" + access_macros +
"\n";
1388 builder.
ss <<
"\n#pragma resource_defines " + cls.identifier +
"\n";
1391 string size_to_float_vec_type_str(
size_t member_size)
1393 if (member_size == 4) {
1396 if (member_size == 8) {
1399 if (member_size == 12) {
1402 if (member_size == 16) {
1408 void union_members_decl(SymbolClass &cls)
1410 for (
int i = 0; i < cls.size; i += 16) {
1411 int member_size =
min(16, cls.size - i);
1412 builder.
ss << size_to_float_vec_type_str(member_size) <<
" _" <<
to_string(i / 16) <<
"; ";
1416 string union_ctor(SymbolClass &cls)
1419 for (
int i = 0; i < cls.size; i += 16) {
1420 int member_size =
min(16, cls.size - i);
1422 members +=
"r._" +
to_string(i / 16) +
"=" + default_value(*type) +
";";
1427 string default_value(
const SymbolClass &type)
1429 if (type.identifier ==
"float") {
1432 if (type.identifier ==
"uint" || type.identifier ==
"uchar") {
1435 if (type.identifier ==
"int" || type.identifier ==
"char") {
1438 if (type.identifier ==
"bool") {
1441 if (type.is_builtin()) {
1442 return type.identifier +
"(0)";
1444 return type.identifier +
"_ctor_()";
1448 static string get_temp_name(
size_t index)
1452 size_t n =
index + 1;
1455 name += char(
'a' + (n % 26));
1461 string class_default_constructor(ClassDecl decl, SymbolClass &cls)
1463 const string &cls_id = cls.identifier;
1467 members = union_ctor(cls);
1472 switch (
node.type()) {
1473 case NodeType::VarDecl: {
1476 SymbolClass *type = id_type_lookup_resolved(decl.
type().
identifier(), cls);
1478 SymbolVariable *var = cls.lookup_variable(
table, d.identifier());
1479 if (var->is_static || var->bit_offset != 0) {
1487 string len = var->capacity_value.is_valid() ?
1488 "SRT_CONSTANT_" + string(var->capacity_value.str()) :
1489 string(sub.expr().
str());
1490 string var = get_temp_name(dim++);
1491 members +=
"for(int " + var +
" =0;" + var +
" < " +
len +
";++" + var +
") {";
1493 access +=
"[" + var +
"]";
1496 members +=
"r." + var->original + access +
"=" + default_value(*type) +
";";
1502 case NodeType::ClassDecl: {
1506 jump_to(decl.
front());
1507 string type_id =
"a" +
to_string(class_id);
1508 SymbolClass *type = cls.lookup_class(type_id);
1509 string member_id = type_id +
"_";
1511 members +=
"r." + member_id +
"=" + default_value(*type) +
";";
1521 if (members.empty()) {
1523 members +=
"r._pad=0;";
1527 return cls_id +
" " + cls_id +
"_ctor_() {" + cls_id +
" r;" + members +
"return r;}";
1530 string union_data_access(
const size_t member_offset,
1531 const size_t member_size,
1532 const size_t union_size)
1534 string access =
"_" +
to_string(member_offset / 16);
1536 if (member_size == 12) {
1539 else if (member_size == 8) {
1540 access += ((member_offset % 16) == 0) ?
".xy" :
".zw";
1542 else if (member_size == 4) {
1543 switch (member_offset % 16) {
1546 access += ((union_size - member_offset) == 4) ?
"" :
".x";
1562 string member_from_float(
const SymbolClass &member_type,
const string &access)
1565 const string &type = member_type.identifier;
1567 if (type.starts_with(
"uint")) {
1568 return "floatBitsToUint(" + access +
")";
1570 if (type.starts_with(
"int")) {
1571 return "floatBitsToInt(" + access +
")";
1573 if (type ==
"bool32_t") {
1574 return access +
" != 0";
1579 string member_to_float(
const SymbolClass &member_type,
const string &access)
1582 const string &type = member_type.identifier;
1584 if (type.starts_with(
"uint")) {
1585 return "uintBitsToFloat(" + access +
")";
1587 if (type.starts_with(
"int")) {
1588 return "intBitsToFloat(" + access +
")";
1590 if (type ==
"bool32_t") {
1591 return "intBitsToFloat(int(" + access +
"))";
1596 string union_getter(SymbolClass &union_type, SymbolVariable &member)
1598 SymbolClass &member_type = *member.type;
1599 string union_type_id = union_type.identifier;
1600 string fn_type_id = member_type.identifier;
1601 string fn_name =
"_" + member.original;
1602 string fn_args =
"(" + union_type_id +
" this_)";
1603 string fn_body =
"{\n";
1604 if (member_type.is_builtin()) {
1605 if (member.array_dimensions > 0) {
1608 string access =
"this_." +
1609 union_data_access(member.offset, member_type.size, union_type.size);
1610 fn_body +=
" return " + member_from_float(*member.type, access) +
";\n";
1614 fn_body +=
" " + fn_type_id +
" r;\n";
1615 for (
const auto &var : member_type.get_all_members_flat().unwrap(
this)) {
1616 string to_var =
"r." + var.path;
1617 string access =
"this_." +
1618 union_data_access(var.absolute_offset, var.type->size, union_type.size);
1619 fn_body +=
" " + to_var +
" = " + member_from_float(*var.type, access) +
";\n";
1621 fn_body +=
" return r;\n";
1624 return fn_type_id +
" " + fn_name + fn_args +
" " + fn_body;
1627 string union_setter(SymbolClass &union_type, SymbolVariable &member)
1629 SymbolClass &member_type = *member.type;
1630 string union_type_id = union_type.identifier;
1631 string member_type_id = member_type.identifier;
1632 string fn_name =
"_" + member.original +
"_set_";
1633 string fn_args =
"(" + union_type_id +
" &this_, " + member_type_id +
" v)";
1634 string fn_body =
"{\n";
1635 if (member_type.is_builtin()) {
1636 if (member.array_dimensions > 0) {
1639 string to_var =
"this_." +
1640 union_data_access(member.offset, member_type.size, union_type.size);
1641 string access =
"v." + member.original;
1642 fn_body +=
" " + to_var +
" = " + member_to_float(*member.type, access) +
";\n";
1645 for (
const auto &var : member_type.get_all_members_flat().unwrap(
this)) {
1646 string to_var =
"this_." +
1647 union_data_access(var.absolute_offset, var.type->size, union_type.size);
1648 string access =
"v." + var.path;
1649 fn_body +=
" " + to_var +
" = " + member_to_float(*var.type, access) +
";\n";
1653 return "void " + fn_name + fn_args +
" " + fn_body;
1656 void func_forward_decl(FuncDecl decl, SymbolScope &scope)
1659 if (
auto it = scope.functions.find(
id); it != scope.functions.end()) {
1660 SymbolScope &body_scope = *it->second.second;
1667 func_arg_list(decl.
arguments(), body_scope,
false,
true);
1675 void func_forward_decl(FuncForwardDecl decl, SymbolScope &scope)
1680 if (
auto it = scope.functions.find(
id); it != scope.functions.end()) {
1681 SymbolScope &body_scope = *it->second.second;
1682 jump_to(decl.
front());
1688 func_arg_list(decl.
arguments(), body_scope,
false,
true);
1697 string condition(
const SymbolScope *scope)
1700 for (
const auto &[k, var] : scope->variables) {
1701 if (var.second->type->is_srt()) {
1703 str +=
" && defined(IFACE_INFO_" + var.second->type->identifier +
"_t)";
1706 str +=
" && defined(CREATE_INFO_" + var.second->type->identifier +
")";
1710 return str.empty() ?
str :
str.substr(4);
1713 string condition(
const SymbolFunction *fn)
1717 for (
int i = 0; i < fn->arg_types.size(); ++i) {
1719 str +=
" && defined(GPU_VERTEX_SHADER)";
1724 for (
int i = 0; i < fn->arg_types.size(); ++i) {
1726 str +=
" && defined(GPU_FRAGMENT_SHADER)";
1731 if (fn->is_entry_point()) {
1732 str +=
" && defined(ENTRY_POINT_" + fn->identifier +
")";
1733 switch (fn->entry_point_type) {
1735 str +=
" && defined(GPU_FRAGMENT_SHADER)";
1738 str +=
" && defined(GPU_VERTEX_SHADER)";
1741 str +=
" && defined(GPU_COMPUTE_SHADER)";
1747 else if (
string scope_str = condition(
static_cast<const SymbolScope *
>(fn));
1750 str +=
" && " + scope_str;
1753 return str.empty() ?
str :
str.substr(4);
1756 void func_decl(FuncDecl decl,
1759 SymbolFunction *inst_fn =
nullptr)
1763 if (inst_fn ==
nullptr) {
1767 if (inst_fn->is_inline) {
1773 if (SymbolClass *cls = inst_fn->parent_class(); cls) {
1777 builder.
ss <<
"#pragma member_forward_decl " << inst_fn->parent_class()->identifier
1779 builder.
ss << inst_fn->return_type->identifier <<
" " << inst_fn->identifier;
1781 func_arg_list(decl.
arguments(), *inst_fn,
false);
1789 string cond = condition(inst_fn);
1790 if (!cond.empty()) {
1791 builder.
ss << string(
"#if ") + cond +
"\n";
1794 jump_to(decl.
front());
1804 if (inst_fn->is_entry_point()) {
1809 func_arg_list(decl.
arguments(), *inst_fn);
1812 local_scope(body, *inst_fn);
1814 if (!cond.empty()) {
1818 if (inst_fn->is_entry_point()) {
1819 entry_point_arg_list_metadata(decl, *inst_fn);
1823 pair<SymbolFunction *, FuncCall> get_inlined_function(Expr expr, SymbolScope &scope)
1827 return {
nullptr, {}};
1829 if (!expr.has_single_child() || expr.parent().parent().type() == NodeType::Condition) {
1830 return {
nullptr, {}};
1833 SymbolFunction *fn = id_func_resolved_lookup(
1835 if (!fn || !fn->is_inline) {
1836 return {
nullptr, {}};
1841 vector<SymbolFunction *> inlining_stack;
1843 string inline_function(SymbolFunction *fn, FuncCall call, SymbolScope &scope)
1846 string ret_val =
"_r" + uuid;
1848 if (std::ranges::find(inlining_stack, fn) != inlining_stack.end()) {
1853 inlining_stack.push_back(fn);
1856 jump_to(fn->decl.front());
1861 SymbolVariable *var = it->second.second;
1862 var->identifier = ret_val;
1864 builder.
ss << fn->return_type->identifier <<
" " << ret_val <<
";\n";
1869 jump_to(fn->decl.front());
1874 vector<string> original_identifiers;
1875 for (FuncArg arg : fn->decl.arguments().children_range()) {
1876 SymbolVariable *var = fn->lookup_variable(
table, arg.identifier());
1878 if (!param.
is_valid() && (arg.is_reference() || !fn->arg_defaults[arg_i].is_valid())) {
1883 original_identifiers.emplace_back(var->identifier);
1885 if (arg.is_reference() || var->type->is_opaque) {
1888 var->identifier = expr(param, scope).str;
1892 string id =
"_" + string(arg.identifier().str()) + uuid;
1894 var->identifier = id;
1896 Expr init_expr = (param.
is_valid()) ? param : fn->arg_defaults[arg_i];
1897 builder.
ss << fn->arg_types[arg_i]->identifier <<
" " << id;
1898 builder.
ss <<
" = " << expr(init_expr, scope).str <<
"; ";
1900 param = param.
next();
1905 local_scope(fn->decl.body(), *fn);
1910 inlining_stack.pop_back();
1915 for (FuncArg arg : fn->decl.arguments().children_range()) {
1916 SymbolVariable *var = fn->lookup_variable(
table, arg.identifier());
1917 var->identifier = original_identifiers[arg_i++];
1924 void entry_point_arg_list_metadata(FuncDecl decl, SymbolFunction &fn)
1927 string create_info_decl;
1930 string_view
id = attr.identifier().str();
1931 if (
id ==
"clip_control") {
1932 create_info_decl +=
"BUILTINS(BuiltinBits::CLIP_CONTROL)\n";
1934 else if (
id ==
"texture_atomic") {
1935 create_info_decl +=
"BUILTINS(BuiltinBits::TEXTURE_ATOMIC)\n";
1937 else if (
id ==
"early_fragment_tests") {
1938 create_info_decl +=
"EARLY_FRAGMENT_TEST(true)\n";
1940 else if (
id ==
"local_size") {
1941 create_info_decl +=
"LOCAL_GROUP_SIZE" + string(attr.parameters().str()) +
"\n";
1943 else if (
id ==
"metal_max_total_threads_per_threadgroup") {
1944 create_info_decl +=
"MTL_MAX_TOTAL_THREADS_PER_THREADGROUP" +
1945 string(attr.parameters().str()) +
"\n";
1952 SymbolVariable *var = fn.lookup_variable(
table, arg.identifier());
1954 const string &resolved_type = var->type->identifier;
1956 switch (attr.res_type) {
1974 string res_condition_lambda = parse_condition_as_lambda(fn, arg.attributes());
1975 create_info_decl +=
".builtins(BuiltinBits::" + to_str(attr.res_type) +
1976 res_condition_lambda +
")\n";
1980 string res_condition_lambda = parse_condition_as_lambda(fn, arg.attributes());
1981 create_info_decl +=
".builtins(BuiltinBits::BARYCENTRIC_COORD" + res_condition_lambda +
1986 for (Attr attr : arg.attributes().children_of_type<Attr>()) {
1987 string_view
id = attr.identifier().str();
1988 if (
id ==
"frag_depth") {
1989 create_info_decl +=
"DEPTH_WRITE(DepthWrite::" +
1990 to_uppercase(
string(attr.parameters().splat_1().arg1.str())) +
1996 string res_condition_lambda = parse_condition_as_lambda(fn, arg.attributes());
1997 if (res_condition_lambda.empty()) {
1998 create_info_decl +=
"ADDITIONAL_INFO(" + resolved_type +
")\n";
2001 create_info_decl +=
".additional_info_with_condition(\"" + resolved_type +
"\"" +
2002 res_condition_lambda +
")\n";
2010 string res_condition_lambda = parse_condition_as_lambda(fn, arg.attributes());
2011 if (res_condition_lambda.empty()) {
2012 create_info_decl +=
".vertex_out(" + resolved_type +
"_t)\n";
2015 create_info_decl +=
".vertex_out(" + resolved_type +
"_t" + res_condition_lambda +
2020 create_info_decl +=
"ADDITIONAL_INFO(" + resolved_type +
")\n";
2050 if (create_info_decl.empty()) {
2051 create_info_decl +=
"DEFINE(\"EMPTY_CREATE_INFO\")\n";
2054 create_info_decl =
"GPU_SHADER_CREATE_INFO(" + fn.identifier +
"_infos_)\n" +
2055 create_info_decl +
"GPU_SHADER_CREATE_END()\n";
2059 void func_arg_list(FuncArgList list,
2061 bool with_trivia =
true,
2062 bool no_arg_name =
false)
2072 SymbolClass *cls_resolved = id_type_resolved(cls.
identifier(), scope);
2073 if (cls_resolved->is_srt()) {
2092 skip_node(arg.attributes());
2093 id_type(arg.type(), scope);
2094 declarator(arg.declarator(), scope,
true, no_arg_name ? i++ : -1);
2101 skip_if(TokenType::Const);
2111 void template_inst(TemplateInst temp_decl, SymbolScope &scope)
2117 auto [temp_cls, full_id, _] = base_cls->template_data->lookup_inst(
2120 Node decl_tmp = base_cls->template_data->decl.decl();
2121 class_decl(decl_tmp, scope, 0, temp_cls);
2127 auto [temp_fn, full_id, _] = base_fn->template_data->lookup_inst(
2130 Node decl_tmp = base_fn->template_data->decl.decl();
2131 func_decl(decl_tmp, *temp_fn->parent, temp_fn);
2135 void template_spec(TemplateSpec temp_spec, SymbolScope &scope)
2141 auto [temp_cls, full_id, _] = base_cls->template_data->lookup_inst(
2144 class_decl(decl, scope, 0, temp_cls);
2150 auto [temp_fn, full_id, _] = base_fn->template_data->lookup_inst(
2153 func_decl(decl, *temp_fn->parent, temp_fn);
2158 void if_statement(Node decl,
2159 SymbolScope &parent_scope,
2160 int &local_scope_id,
2161 bool preceded_by_true_if_constexpr =
false,
2162 bool preceded_by_regular_if =
false)
2164 SymbolScope *scope = parent_scope.child_scope(local_scope_id++);
2165 if (scope ==
nullptr) {
2170 jump_to(decl.front());
2174 bool is_constexpr = cond.is_valid() && cond.front().prev() ==
Constexpr;
2176 bool constexpr_value =
true;
2177 if (cond.is_valid()) {
2181 if (is_constexpr && !
result.is_constexpr()) {
2185 else if (
result.is_constexpr()) {
2187 is_constexpr =
true;
2190 if (
result.is_constexpr()) {
2191 constexpr_value =
result.value.comp_as<
int>(0) != 0;
2194 if (cond.attributes().contains_attr(
"static_branch")) {
2202 if (preceded_by_regular_if && !preceded_by_true_if_constexpr &&
2203 (!is_constexpr || constexpr_value ==
true))
2213 if (!is_constexpr && !preceded_by_true_if_constexpr) {
2216 if (cond.is_valid()) {
2217 condition(cond, *scope,
false,
true);
2226 LocalScope body = decl.child_last(NodeType::LocalScope);
2228 if (!preceded_by_true_if_constexpr && (!is_constexpr || constexpr_value ==
true)) {
2229 local_scope(body, *scope);
2234 while (
node.type() == NodeType::Preprocessor) {
2239 Node next = decl.next();
2240 if (next.
type() == NodeType::ElseIfStmt || next.
type() == NodeType::ElseStmt) {
2244 preceded_by_true_if_constexpr || (is_constexpr && constexpr_value ==
true),
2245 preceded_by_regular_if || !is_constexpr);
2248 jump_to(next.front());
2252 struct StaticConditionStack {
2264 vector<ast::Expr> pos_conditions;
2265 vector<ast::Expr> neg_conditions;
2273 void pop_positive_condition()
2275 pos_conditions.pop_back();
2283 void pop_negative_condition()
2285 neg_conditions.pop_back();
2290 vector<SubCondition> check_condition(
ast::Expr expr)
2300 vector<SubCondition> expr_split = split_expr(expr,
LogicalAnd);
2303 remove_included_expr(expr_split, split_expr(cond,
LogicalAnd),
false);
2308 remove_included_expr(expr_split, split_expr(cond,
LogicalOr),
true);
2317 vector<SubCondition>
split;
2320 ast::Node back = front;
2324 if (back.
front() == split_token) {
2327 front = back.
next();
2332 split.emplace_back(front, back);
2337 void remove_included_expr(vector<SubCondition> &expr_split,
2338 const vector<SubCondition> &cond_split,
2341 std::erase_if(expr_split, [&](
const SubCondition &expr) {
2342 return std::ranges::any_of(cond_split, [&](
const SubCondition &cond) {
2343 return check_expression_inclusion(expr, cond, negative_cond);
2358 ast::Node node_expr = expr.front;
2359 ast::Node node_cond = cond.front;
2360 if (negative_cond) {
2361 if (node_expr.
front() ==
'!' && node_expr.
front().
str().length() == 1) {
2362 node_expr = node_expr.
next();
2370 switch (node_expr.
type()) {
2371 case NodeType::LocalVar:
2374 while (node_cond.
next().
front() ==
'.') {
2375 node_cond = node_cond.
next().
next();
2377 if (node_cond.
type() != NodeType::LocalVar) {
2384 case NodeType::NumConst:
2386 match &= node_expr.
str() == node_cond.
str();
2394 bool end_of_cond = node_cond.
front() == cond.back.front();
2395 bool end_of_expr = node_expr.
front() == expr.back.front();
2397 if (end_of_cond || end_of_expr) {
2399 match &= end_of_cond && end_of_expr;
2403 node_expr = node_expr.
next();
2404 node_cond = node_cond.
next();
2406 match = (node_expr.
type() == node_cond.
type());
2410 } static_condition_stack;
2415 vector<StaticConditionStack::SubCondition> expr_split = static_condition_stack.check_condition(
2418 if (!expr_split.empty()) {
2424 void static_if_statement(Node decl,
2425 SymbolScope &parent_scope,
2426 int &local_scope_id,
2429 SymbolScope *scope = parent_scope.child_scope(local_scope_id++);
2430 if (scope ==
nullptr) {
2437 if (cond.is_valid()) {
2438 if (!cond.attributes().contains_attr(
"static_branch")) {
2445 int unused_count = 0;
2447 auto cond_str =
table
2451 builder.
ss << (first ?
"#if " :
"#elif ") + cond_str +
"\n";
2453 static_condition_stack.push_positive_condition(cond);
2463 LocalScope body = decl.child_last(NodeType::LocalScope);
2464 jump_to(body.
front());
2466 local_scope(body, *scope);
2468 if (cond.is_valid()) {
2470 static_condition_stack.pop_positive_condition();
2471 static_condition_stack.push_negative_condition(cond);
2476 while (
node.type() == NodeType::Preprocessor) {
2483 Node next = decl.next();
2484 if (next.
type() == NodeType::ElseIfStmt || next.
type() == NodeType::ElseStmt) {
2485 static_if_statement(next, parent_scope, local_scope_id,
false);
2489 builder.
ss << string(decl.front().char_number(),
' ') +
"#endif\n";
2490 jump_to(next.front());
2493 if (cond.is_valid()) {
2495 static_condition_stack.pop_negative_condition();
2499 void condition(Condition cond, SymbolScope &scope,
bool is_for_loop,
bool do_implicit_conversion)
2503 if (child.type() == NodeType::VarDecl) {
2504 var_decl(child, scope,
false);
2506 else if (child.type() == NodeType::LocalStmt) {
2507 local_statement(child, scope);
2510 if (do_implicit_conversion &&
2511 (!is_for_loop || (child.prev().is_valid() && child.next().is_valid())))
2513 Node start =
LocalStmt(child).expr().child_first();
2543 bool var_decl(VarDecl decl, SymbolScope &scope,
bool jump =
true)
2553 if (scope.as_class() ==
nullptr && decl.
is_reference()) {
2562 if (var->is_bitfield && var->bit_offset != 0) {
2570 jump_to(decl.
front());
2581 id_type(decl.
type(), scope);
2584 declarator(d, scope);
2591 void id_type(IdType type, SymbolScope &scope)
2599 void array_decl(SymbolVariable &var, ArrayDecl array, Declarator decl, SymbolScope &scope)
2619 if (var.capacity_value.is_valid()) {
2624 if (var.capacity_value.is_valid()) {
2626 builder <<
"SRT_CONSTANT_" + string(var.capacity_value.str());
2641 if (!err &&
result.is_constexpr()) {
2642 if (
result.value.comp_as<
int>(0) <= 0) {
2653 void declarator(Declarator decl,
2655 bool skip_value =
false,
2656 int skip_name_match_index = -1)
2659 SymbolVariable *var = scope.lookup_variable(
table, decl.
identifier());
2661 if (var->is_bitfield && var->bit_offset != 0) {
2667 const bool par = match_if(
'(');
2672 if (type->is_srt()) {
2681 if (skip_name_match_index != -1) {
2686 id_var_decl_resolved(decl.
identifier(), scope);
2693 array_decl(*var, array, decl, scope);
2697 if (!var->is_error && var->is_constexpr) {
2699 builder <<
"= " + var->value_str();
2717 void assignment(AssignStmt stmt, SymbolScope &scope, SymbolVariable *var)
2720 if (
auto [fn, call] = get_inlined_function(stmt.
expr(), scope); fn) {
2728 string val = inline_function(fn, call, scope);
2730 jump_to(var->loc.tok);
2731 builder.
ss << var->identifier <<
" = " << val;
2738 builder.
ss << init_expression_or_initializer_list(
2745 const SymbolScope &scope,
2749 if (
node == NodeType::InitializerList) {
2750 return initializer_list(
node, scope, cls, array_dim);
2752 if (
node == NodeType::Expr) {
2753 return expr(
node, scope);
2760 const SymbolScope &scope,
2764 const bool is_empty = list.
is_empty();
2765 if (array_dim > 0) {
2768 else if (cls ==
nullptr || cls->is_error) {
2776 if (array_dim > 0) {
2778 open =
'{', close =
'}';
2780 else if (cls->is_builtin()) {
2782 open = cls->identifier +
"(", close =
')';
2784 else if (is_empty) {
2786 if (cls->is_builtin()) {
2787 open = cls->identifier +
"(0", close =
')';
2790 open = cls->identifier +
"_ctor_(", close =
')';
2797 open =
"_ctor(" + cls->identifier +
",";
2800 open += trivia(list.
front());
2801 close += trivia(list.
back());
2805 if (designated.is_valid()) {
2806 if (array_dim > 0) {
2811 for (SymbolVariable *var : cls->non_static_variables_in_declaration_order()) {
2812 if (designated.is_valid() && var->identifier == designated.identifier().str()) {
2814 content += init_expression_or_initializer_list(stmt.
child_first(), scope, var->
type).
str;
2815 string_view comma = opt_str(designated.back().next(),
Comma);
2816 content += comma.empty() ?
"," : comma;
2817 designated = designated.next();
2820 content += default_value(*var->type) +
",";
2824 content = content.substr(0, content.rfind(
","));
2826 if (designated.is_valid()) {
2827 if (
auto *var = cls->lookup_variable(
string(designated.identifier().str()));
2828 var && !var->is_error)
2835 designated.identifier().str(),
2842 content += init_expression_or_initializer_list(child.child_last(),
2844 array_dim > 0 ? cls :
nullptr ,
2847 content += opt_str(child.back().next(),
Comma);
2850 return {open + content + close, cls};
2858 SymbolClass *id_type_lookup_resolved(IdQualified
id,
const SymbolScope &scope)
2861 auto *cls = scope.lookup_class(
table,
id).unwrap(
this);
2862 if (cls->template_data && !
id.template_params().is_valid()) {
2865 else if (cls->is_error) {
2871 SymbolClass *id_type_resolved(IdQualified
id,
const SymbolScope &scope)
2873 auto *cls_resolved = id_type_lookup_resolved(
id, scope);
2875 builder << cls_resolved->identifier + trivia(
id);
2876 return cls_resolved;
2880 SymbolClass *id_type_resolved(
string id,
const SymbolScope &scope)
2882 auto it = scope.classes.find(
id);
2883 SymbolClass *cls = it->second.second;
2888 template<
typename ArgOrParamList>
2889 SymbolFunction *id_func_resolved_lookup(IdQualified
id,
2890 ArgOrParamList params,
2891 const SymbolScope &scope,
2892 const SymbolScope ¶m_scope,
2893 optional<SourceLocation> loc = nullopt)
2896 return scope.lookup_function(
table,
id, params, param_scope, loc).unwrap(
this);
2899 template<
typename ArgOrParamList>
2900 SymbolFunction *id_func_resolved(IdQualified
id,
2901 ArgOrParamList params,
2902 const SymbolScope &scope,
2903 const SymbolScope ¶m_scope,
2904 optional<SourceLocation> loc = nullopt)
2906 SymbolFunction *func = id_func_resolved_lookup(
id, params, scope, param_scope, loc);
2908 builder << func->identifier + trivia(
id);
2913 SymbolVariable *id_var_resolved(IdQualified
id,
const SymbolScope &scope)
2916 SymbolVariable *var = scope.lookup_variable(
table,
id);
2917 if (var->is_error) {
2923 if (var->is_constexpr) {
2924 builder.
ss << var->value_str() + trivia(
id);
2928 if (var->type->is_srt()) {
2929 if (
id.back().next() == TokenType::Dot &&
id.parent().next().next() != NodeType::FuncCall) {
2935 builder << var->type->identifier +
"_ctor_()" + trivia(
id);
2940 if (var->reference_value.is_valid()) {
2941 builder << string(var->reference_value.str()) + trivia(
id);
2945 bool preceded_by_dot =
id.front().prev() ==
'.';
2946 if (!var->is_static && !preceded_by_dot && var->parent->as_class() !=
nullptr) {
2951 builder << var->identifier + trivia(
id);
2956 SymbolVariable *id_var_decl_resolved(IdQualified
id,
const SymbolScope &scope)
2959 SymbolVariable *var = scope.lookup_variable(
table,
id);
2960 if (var->is_error) {
2967 if (var->is_static) {
2969 builder << var->identifier + trivia(
id);
2982 void parse_class_metadata(SymbolClass &cls, LocalScope body)
2984 string &cls_id = cls.identifier;
2985 metadata::ResourceTable srt;
2986 metadata::VertexInputs vertex_in;
2987 metadata::StageInterface vertex_out;
2988 metadata::FragmentOutputs fragment_out;
2989 metadata::FragmentInputs fragment_in;
2991 vertex_in.
name = cls_id;
2992 vertex_out.
name = cls_id;
2993 fragment_out.
name = cls_id;
2994 fragment_in.
name = cls_id;
2999 const string &type_name = var->
type->identifier;
3000 const string &var_name = var->identifier;
3001 switch (cls.srt_type) {
3003 srt.emplace_back(parse_resource(decl.attributes(), type_name, var_name, d.
array(), cls));
3006 vertex_in.emplace_back(parse_vertex_input(decl.attributes(), type_name, var_name, cls));
3009 vertex_out.emplace_back(parse_vertex_output(decl.attributes(), type_name, var_name));
3012 fragment_out.emplace_back(parse_fragment_output(decl.attributes(), type_name, var_name));
3015 fragment_in.emplace_back(parse_fragment_input(decl.attributes(), type_name, var_name));
3022 switch (cls.srt_type) {
3044 metadata::ParsedVertInput parse_vertex_input(AttrList attributes,
3047 const SymbolClass &cls)
3054 .slot = string(attr.param1.str()),
3055 .res_condition = parse_condition(cls, attr.condition),
3059 metadata::ParsedAttribute parse_vertex_output(AttrList attributes,
3068 .interpolation_mode = string(attr.attr.str()),
3072 metadata::ParsedFragOuput parse_fragment_output(AttrList attributes,
3081 .slot = string(attr.param1.str()),
3082 .dual_source = string(attr.dual_source_index.str()),
3083 .raster_order_group = string(attr.raster_order_group.str()),
3087 metadata::ParsedFragInput parse_fragment_input(AttrList attributes,
3096 .slot = string(attr.param1.str()),
3097 .image_type = string(attr.param2.str()),
3098 .raster_order_group = string(attr.raster_order_group.str()),
3102 string parse_image_format(SymbolClass &cls, Expr expr)
3104 Node
node = expr.child_first();
3105 if (LocalVar var =
node; var.is_valid()) {
3106 SymbolVariable *
sym = cls.lookup_variable(
table, var.identifier());
3107 if (
sym->is_macro) {
3109 return string(expr.str());
3111 if (
sym->is_constexpr) {
3112 int enum_val =
sym->value.comp_as<
int>(0);
3127 string array_size_to_string(
ast::ArrayDecl array,
const SymbolScope &scope)
3137 if (
result.is_constexpr()) {
3150 str += string(sub.
str());
3156 metadata::ParsedResource parse_resource(AttrList attributes,
3163 switch (attr.res_type) {
3172 .var_array = array_size_to_string(array, cls),
3173 .res_type = string(attr.attr.identifier().str()),
3174 .res_condition = parse_condition(cls, attr.condition)};
3179 .var_array = array_size_to_string(array, cls),
3180 .res_type = string(attr.attr.identifier().str()),
3181 .res_value = string(attr.param1.str()),
3182 .res_condition = parse_condition(cls, attr.condition)};
3187 .var_array = array_size_to_string(array, cls),
3188 .res_type = string(attr.attr.identifier().str()),
3189 .res_slot = string(attr.param1.str()),
3190 .res_condition = parse_condition(cls, attr.condition),
3191 .res_frequency = parse_frequency(attr.frequency)};
3196 .var_array = array_size_to_string(array, cls),
3197 .res_type = string(attr.attr.identifier().str()),
3198 .res_slot = string(attr.param1.str()),
3199 .res_condition = parse_condition(cls, attr.condition),
3200 .res_frequency = parse_frequency(attr.frequency)};
3205 .var_array = array_size_to_string(array, cls),
3206 .res_type = string(attr.attr.identifier().str()),
3207 .res_slot = string(attr.param1.str()),
3208 .res_condition = parse_condition(cls, attr.condition),
3209 .res_frequency = parse_frequency(attr.frequency)};
3214 .var_array = array_size_to_string(array, cls),
3215 .res_type = string(attr.attr.identifier().str()),
3216 .res_slot = string(attr.param1.str()),
3217 .res_qualifier = string(attr.param2.str()),
3218 .res_condition = parse_condition(cls, attr.condition),
3219 .res_frequency = parse_frequency(attr.frequency)};
3224 .var_array = array_size_to_string(array, cls),
3225 .res_type = string(attr.attr.identifier().str()),
3226 .res_slot = string(attr.param1.str()),
3227 .res_qualifier = string(attr.param2.str()),
3228 .res_format = parse_image_format(cls, attr.param3),
3229 .res_condition = parse_condition(cls, attr.condition),
3230 .res_frequency = parse_frequency(attr.frequency)};
3239 string parse_condition(
const SymbolScope &scope,
ast::Expr condition)
const
3241 if (!condition.is_valid()) {
3245 for (LocalVar
node : condition.children_of_type<LocalVar>()) {
3246 if (SymbolVariable *var = scope.lookup_variable(
table,
node.identifier());
3247 !var->is_error && var->is_constexpr)
3249 str +=
"int " + string(
node.str()) +
" = " + var->value_str() +
"; ";
3253 str +=
"int " + string(
node.str()) +
" = ";
3254 str +=
"ShaderCreateInfo::find_constant(constants, \"" + string(
node.str()) +
"\"); ";
3257 str +=
"return " + string(condition.str()) +
";";
3261 string parse_condition_as_lambda(
const SymbolScope &scope, AttrList attributes)
3265 if (attr.identifier().str() ==
"condition") {
3266 if (!cond.empty()) {
3270 cond = parse_condition(scope, attr.parameters().splat_1().arg1);
3273 if (!cond.empty()) {
3274 cond =
", [](blender::Span<CompilationConstant> constants) { " + cond +
"}";