From 1cbdff697b5f06d0cf1588af7081072375a37776 Mon Sep 17 00:00:00 2001 From: Peter Li Date: Sun, 1 Nov 2026 00:58:07 -0700 Subject: [PATCH] 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::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 class type and S) shared one layout, which crashed dxv. Co-Authored-By: Claude Opus 5.5 --- src/dxil/emit.zig | 15 ++++++++++++++- src/front/ast.zig | 3 ++- src/front/parser.zig | 22 ++++++++++++++++++---- src/sema/sema.zig | 24 +++++++++++++++++++++++- test/dxil/lib_mangling.hlsl | 6 +++++- 5 files changed, 62 insertions(+), 8 deletions(-) diff --git a/src/dxil/emit.zig b/src/dxil/emit.zig index 6dd997b..4640151 100644 --- a/src/dxil/emit.zig +++ b/src/dxil/emit.zig @@ -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::In`, `A::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)}), }; diff --git a/src/front/ast.zig b/src/front/ast.zig index c88c609..776e525 100644 --- a/src/front/ast.zig +++ b/src/front/ast.zig @@ -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;` diff --git a/src/front/parser.zig b/src/front/parser.zig index 567f7e7..b3a97f6 100644 --- a/src/front/parser.zig +++ b/src/front/parser.zig @@ -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::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 { diff --git a/src/sema/sema.zig b/src/sema/sema.zig index f9f195e..62c2eb2 100644 --- a/src/sema/sema.zig +++ b/src/sema/sema.zig @@ -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 struct B { typedef T F; T x; }; + \\struct C { using F = float; F x; }; + \\template struct D { struct In { T t; }; using E = T; }; + \\void f() { C::F c = 1; D::In i; i.t = c; D::E e = 2; } + , .{}, &.{ + "1: error: nested typedefs are not supported in HLSL", + "2: error: nested typedefs are not supported in HLSL", + }); +} diff --git a/test/dxil/lib_mangling.hlsl b/test/dxil/lib_mangling.hlsl index 6b10462..3331540 100644 --- a/test/dxil/lib_mangling.hlsl +++ b/test/dxil/lib_mangling.hlsl @@ -2,14 +2,17 @@ // Mangled names of exported functions whose parameters are structs and // enums in namespaces and structs, class / struct template instances // (type and integral arguments, negative ones too) and classes, with the -// back-references dxc uses; RDAT carries them byte for byte. +// back-references dxc uses; RDAT carries them byte for byte. Same-named +// nested structs of two instances are distinct types. // ZCHECK: define float @"\01?f2@@YAMU?$Box@M$02@inner@ns@@@Z"( // ZCHECK: define i32 @"\01?f4@@YAHUNested@Outer@inner@ns@@W4E@234@@Z"( +// ZCHECK: %struct.In.0 = type { %struct.P } namespace ns { namespace inner { struct P { float a; }; template struct Box { T v[N]; }; class C { float c; }; struct Outer { struct Nested { int n; }; enum E { E0, E1 }; }; + template struct TO { struct In { T t; }; using Elem = T; }; } } template struct Neg { int x; }; export float f1(ns::inner::P p, ns::inner::P q) { return p.a + q.a; } @@ -18,3 +21,4 @@ export float f3(ns::inner::C c, Neg<-5> n) { return 1; } export int f4(ns::inner::Outer::Nested n, ns::inner::Outer::E e) { return n.n + e; } export float f5(ns::inner::Outer::Nested i, ns::inner::Box b) { return i.n + b.v[1].a; } export float f6(inout ns::inner::P p, ns::inner::Box b) { return 1; } +export float f7(ns::inner::TO::In i, ns::inner::TO::Elem e, ns::inner::TO::In p) { return i.t + e + p.t.a; }