zdxc: nested types of template instances; typedef members as dxc

Types declared in structs, template ones included, are accepted as the
last part of a qualified type name (TO<float>::In), which the parser
lost with the template's scope. typedef members are reported in struct
templates too (at the definition, as dxc), while alias declarations
(using F = float;) are allowed in any struct, as in dxc. Each HLSL
struct gets a module type of its own: struct types are named, and
same-named structs (two instances' nested In, or a ConstantBuffer<S>
class type and S) shared one layout, which crashed dxv.
This commit is contained in:
Peter Li 2026-11-01 00:58:07 -07:00
parent 3c4372d2bc
commit d33c3838e2
4 changed files with 57 additions and 7 deletions

View File

@ -233,6 +233,9 @@ const Emitter = struct {
/// Libraries: `[noinline]` functions kept as functions of their own
/// (IR function -> module function).
lib_calls: std.AutoHashMapUnmanaged(u32, u32) = .empty,
/// Each HLSL struct's module type (struct types are named, and two
/// structs may share a name: `A<int>::In`, `A<float>::In`).
struct_types: std.AutoHashMapUnmanaged(TypeId, DType) = .empty,
/// Prologue instructions dropped again if unused (resource handles).
lib_removable: std.AutoHashMapUnmanaged(u32, void) = .empty,
@ -4635,9 +4638,19 @@ const Emitter = struct {
.matrix => |m| e.dm.getType(.{ .array = .{ .len = m.rows, .elem = try e.dm.getType(.{ .array = .{ .len = m.cols, .elem = try e.scalarTy(memScalar(e.compOf(ty))) } }) } }),
.array => |a| e.dm.getType(.{ .array = .{ .len = a.len, .elem = try e.memoryType(a.elem) } }),
.@"struct" => |st| blk: {
if (e.struct_types.get(ty)) |d| break :blk d;
const elems = try e.arena.alloc(DType, st.fields.items.len);
for (elems, st.fields.items) |*x, fld| x.* = try e.memoryType(fld.type);
break :blk e.dm.getType(.{ .@"struct" = .{ .name = try std.fmt.allocPrint(e.arena, "struct.{s}", .{st.name}), .elems = elems } });
// A name another struct has taken gets a suffix, as LLVM's.
const base = try std.fmt.allocPrint(e.arena, "struct.{s}", .{st.name});
var name = base;
var n: u32 = 0;
while (for (e.dm.types.items) |x| {
if (x == .@"struct" and std.mem.eql(u8, x.@"struct".name, name)) break true;
} else false) : (n += 1) name = try std.fmt.allocPrint(e.arena, "{s}.{d}", .{ base, n });
const d = try e.dm.getType(.{ .@"struct" = .{ .name = name, .elems = elems } });
try e.struct_types.put(e.arena, ty, d);
break :blk d;
},
else => e.unsupported("payloads of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}),
};

View File

@ -285,7 +285,8 @@ pub const Decl = struct {
func: FuncDecl,
@"struct": StructDecl,
cbuffer: CBufferDecl,
typedef: struct { name: []const u8, type: *TypeRef, array_dims: []const ?*Expr, template_params: []const TemplateParam = &.{}, qual_words: []const QualWord = &.{}, attrs: []const Attribute = &.{} },
/// `alias`: written `using name = type;`.
typedef: struct { name: []const u8, type: *TypeRef, array_dims: []const ?*Expr, template_params: []const TemplateParam = &.{}, qual_words: []const QualWord = &.{}, attrs: []const Attribute = &.{}, alias: bool = false },
@"enum": EnumDecl,
namespace: struct { name: []const u8, decls: []const *Decl },
/// `using namespace N;`

View File

@ -31,6 +31,10 @@ pub const Parser = struct {
names: std.StringHashMapUnmanaged(std.ArrayList(NameKind)) = .empty,
/// Names declared in each open scope, to undo on exit.
scopes: std.ArrayList(std.ArrayList([]const u8)) = .empty,
/// Types declared in any struct (template ones included, whose scope
/// ends with the template): types as the last part of a qualified
/// name (`S<T>::Inner`).
member_types: std.StringHashMapUnmanaged(void) = .empty,
anon_count: u32 = 0,
/// Name of the struct most recently parsed by parseStructDeclInto
/// (synthesized for anonymous structs), for `typedef struct ...`.
@ -281,6 +285,11 @@ pub const Parser = struct {
return isBuiltinType(name);
}
/// The last part of a qualified name: also a struct's member type.
fn isMemberTypeName(p: *const Parser, name: []const u8) bool {
return p.isTypeName(name) or p.member_types.contains(name);
}
fn isTemplateName(p: *const Parser, name: []const u8) bool {
if (p.lookupName(name)) |k| {
if (k == .template_type or k == .template_func) return true;
@ -306,6 +315,7 @@ pub const Parser = struct {
return p.skipTypeAttrs(p.skipParens(i + 1) orelse return null);
}
if (p.toks[i].kind == .colon_colon) i += 1;
var qualified = false;
while (true) {
const t = p.toks[i];
if (t.kind != .identifier or isReserved(t.text)) return null;
@ -316,9 +326,10 @@ pub const Parser = struct {
}
if (p.toks[after].kind == .colon_colon and p.toks[after + 1].kind == .identifier) {
i = after + 1;
qualified = true;
continue;
}
if (!p.isTypeName(t.text)) return null;
if (!(if (qualified) p.isMemberTypeName(t.text) else p.isTypeName(t.text))) return null;
return p.skipTypeAttrs(after);
}
}
@ -524,7 +535,7 @@ pub const Parser = struct {
return p.mk(ast.TypeRef, .{ .loc = start.loc, .name = try p.simpleName(start.loc, name), .unsigned_spec = !signed });
}
const name = try p.parseName();
if (!p.isTypeName(name.last())) {
if (!(if (name.parts.len > 1) p.isMemberTypeName(name.last()) else p.isTypeName(name.last()))) {
p.diags.position = p.pos;
_ = p.diags.report(.{ .severity = .@"error", .loc = start.loc, .len = @intCast(start.text.len) }, "unknown type name '{s}'", .{name.last()});
return error.Syntax;
@ -849,7 +860,10 @@ pub const Parser = struct {
// that `S::Inner` resolves; the name table is flat by last name.
var nested: std.ArrayList(struct { []const u8, NameKind }) = .empty;
for (p.scopes.items[p.scopes.items.len - 1].items) |n| {
if (p.lookupName(n)) |k| if (k == .type or k == .template_type) try nested.append(p.arena, .{ n, k });
if (p.lookupName(n)) |k| if (k == .type or k == .template_type) {
try nested.append(p.arena, .{ n, k });
if (k == .type) try p.member_types.put(p.arena, n, {});
};
}
p.popScope();
for (nested.items) |n| try p.declareName(n[0], n[1]);
@ -972,7 +986,7 @@ pub const Parser = struct {
const dims = try p.parseArrayDims();
_ = try p.expect(.semi, "';'");
try p.declareNameOuter(name.text, if (template_params.len > 0) .template_type else .type, template_params.len > 0);
return p.mk(ast.Decl, .{ .loc = kw.loc, .kind = .{ .typedef = .{ .name = name.text, .type = ty, .array_dims = dims, .template_params = template_params, .attrs = attrs } } });
return p.mk(ast.Decl, .{ .loc = kw.loc, .kind = .{ .typedef = .{ .name = name.text, .type = ty, .array_dims = dims, .template_params = template_params, .attrs = attrs, .alias = true } } });
}
fn parseNamespace(p: *Parser) Error!*ast.Decl {

View File

@ -295,6 +295,10 @@ pub const Sema = struct {
/// Adds a template (or a specialization) to the name's set here.
fn addTemplate(s: *Sema, name: []const u8, d: *const ast.Decl, spec: bool) !void {
try s.template_scopes.put(s.arena, d, s.scope);
// dxc rejects `typedef` members even in templates never used.
if (d.kind == .@"struct" and s.instance_depth == 0) if (d.kind.@"struct".members) |ms| for (ms) |m| {
if (m.kind == .typedef and !m.kind.typedef.alias and m.kind.typedef.template_params.len == 0) s.err(m.loc, "nested typedefs are not supported in HLSL", .{});
};
const set = blk: {
if (s.scope.syms.get(name)) |sym| switch (sym) {
.template => |t| break :blk t,
@ -1648,7 +1652,9 @@ pub const Sema = struct {
},
.typedef => |td| {
if (td.template_params.len > 0) return s.declareTemplate(td.name, d);
if (ctx == .member and s.instance_depth == 0) {
// (Alias declarations are allowed; template members are
// reported at the template's definition.)
if (ctx == .member and !td.alias and s.instance_depth == 0) {
s.err(d.loc, "nested typedefs are not supported in HLSL", .{});
return;
}
@ -4338,3 +4344,19 @@ test "recursion is reported from exported functions" {
"1: error: recursive functions are not allowed: function 'entry' calls recursive function 'recurse'",
});
}
test "nested types and typedefs" {
// `typedef` members are errors, templates included (even unused);
// alias declarations are not, and nested types of template instances
// resolve.
try expectDiags(
\\struct A { typedef float F; float x; };
\\template <typename T> struct B { typedef T F; T x; };
\\struct C { using F = float; F x; };
\\template <typename T> struct D { struct In { T t; }; using E = T; };
\\void f() { C::F c = 1; D<float>::In i; i.t = c; D<int>::E e = 2; }
, .{}, &.{
"1: error: nested typedefs are not supported in HLSL",
"2: error: nested typedefs are not supported in HLSL",
});
}