Add semantic analysis (Sema) with dxc-derived oracles
Sema type-checks a parsed translation unit: an interned type table, scopes and symbols, declarations, statements and expressions, implicit and explicit conversions, user-function overload resolution, and intrinsic / builtin method matching driven by dxc's gen_intrin_main.txt (vendored, turned into a Zig table at build time by tools/gen_intrinsics.zig). Rules ported from dxc where it matters for exact agreement: - operator result types (CombineBasicTypes, shift and bool rules) - literal suffix types and diagnostics, including `1.#INF` - declaration modifier validity and conflicts (DiagnoseHLSLDecl) and row_major / column_major checks, using source-ordered qualifier words - constant folding of asuint / max / min - `_Static_assert`, `__decltype` and `std::is_same` builtins (`static_assert` is an ordinary identifier in HLSL 2021) Templates, operator overloading and bitfields report "not supported yet (planned for milestone 0.2)". Oracles: - zig build oracle-sema: no false errors on the 1604 dxc-valid corpus files (1537 clean, 67 need milestone 0.2 features) - zig build oracle-verify: error-line agreement with dxc's SemaHLSL -verify tests under HLSL 2021 (53% of expected error lines caught, 80 false error lines) Also fixes the provenance commit of gen_intrin_main.txt (55a61aa79). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
3e7c707036
commit
04e5f9e3c3
28
build.zig
28
build.zig
|
|
@ -22,6 +22,18 @@ pub fn build(b: *std.Build) void {
|
|||
gen_options_run.addFileArg(b.path("vendor/dxc/HLSLOptions.td"));
|
||||
const options_table = gen_options_run.addOutputFileArg("options_table.zig");
|
||||
|
||||
// dxc's intrinsic declarations, likewise generated at build time.
|
||||
const gen_intrinsics = b.addExecutable(.{
|
||||
.name = "gen_intrinsics",
|
||||
.root_module = b.createModule(.{
|
||||
.root_source_file = b.path("tools/gen_intrinsics.zig"),
|
||||
.target = b.graph.host,
|
||||
}),
|
||||
});
|
||||
const gen_intrinsics_run = b.addRunArtifact(gen_intrinsics);
|
||||
gen_intrinsics_run.addFileArg(b.path("vendor/dxc/gen_intrin_main.txt"));
|
||||
const intrinsics_table = gen_intrinsics_run.addOutputFileArg("intrinsics_table.zig");
|
||||
|
||||
const mod = b.addModule("zdxc", .{
|
||||
.root_source_file = b.path("src/root.zig"),
|
||||
.target = target,
|
||||
|
|
@ -29,6 +41,7 @@ pub fn build(b: *std.Build) void {
|
|||
.imports = &.{.{ .name = "hlsl_headers", .module = hlsl_headers }},
|
||||
});
|
||||
mod.addAnonymousImport("options_table", .{ .root_source_file = options_table });
|
||||
mod.addAnonymousImport("intrinsics_table", .{ .root_source_file = intrinsics_table });
|
||||
|
||||
const exe = b.addExecutable(.{
|
||||
.name = "zdxc",
|
||||
|
|
@ -68,6 +81,21 @@ pub fn build(b: *std.Build) void {
|
|||
oracle_parse.has_side_effects = true;
|
||||
oracle_parse_step.dependOn(&oracle_parse.step);
|
||||
|
||||
const oracle_sema_step = b.step("oracle-sema", "Check that Sema accepts every dxc-valid corpus file");
|
||||
const oracle_sema = b.addSystemCommand(&.{ "sh", "test/oracle/sema.sh" });
|
||||
oracle_sema.addArtifactArg(exe);
|
||||
oracle_sema.setCwd(b.path("."));
|
||||
oracle_sema.has_side_effects = true;
|
||||
oracle_sema.step.dependOn(&oracle_parse.step); // builds the corpus list
|
||||
oracle_sema_step.dependOn(&oracle_sema.step);
|
||||
|
||||
const oracle_verify_step = b.step("oracle-verify", "Compare Sema errors with dxc's SemaHLSL -verify expectations");
|
||||
const oracle_verify = b.addSystemCommand(&.{ "sh", "test/oracle/verify.sh" });
|
||||
oracle_verify.addArtifactArg(exe);
|
||||
oracle_verify.setCwd(b.path("."));
|
||||
oracle_verify.has_side_effects = true;
|
||||
oracle_verify_step.dependOn(&oracle_verify.step);
|
||||
|
||||
const oracle_cli_step = b.step("oracle-cli", "Parse every dxc command line in the DXC test corpus");
|
||||
const oracle_cli = b.addSystemCommand(&.{ "sh", "test/oracle/cli.sh" });
|
||||
oracle_cli.addArtifactArg(exe);
|
||||
|
|
|
|||
|
|
@ -41,6 +41,8 @@ pub const TypeRef = struct {
|
|||
attrs: []const Attribute = &.{},
|
||||
/// `unorm` / `snorm` inside resource element types.
|
||||
norm: enum { none, unorm, snorm } = .none,
|
||||
/// `__decltype(expr)`: the type of `expr` (`name` is `__decltype`).
|
||||
decltype: ?*Expr = null,
|
||||
};
|
||||
|
||||
/// Storage classes, type qualifiers and parameter / interpolation
|
||||
|
|
@ -78,9 +80,14 @@ pub const Qualifiers = packed struct(u64) {
|
|||
indices: bool = false,
|
||||
primitives: bool = false,
|
||||
payload: bool = false,
|
||||
_: u34 = 0,
|
||||
center: bool = false,
|
||||
_: u33 = 0,
|
||||
};
|
||||
|
||||
/// A qualifier keyword as written: some diagnostics depend on the order
|
||||
/// and position of qualifiers, which `Qualifiers` does not keep.
|
||||
pub const QualWord = struct { loc: Loc, word: []const u8 };
|
||||
|
||||
/// `[name(args)]` or `[[ns::name(args)]]`.
|
||||
pub const Attribute = struct {
|
||||
loc: Loc,
|
||||
|
|
@ -130,6 +137,10 @@ pub const AssignOp = enum { assign, mul, div, rem, add, sub, shl, shr, bit_and,
|
|||
pub const Expr = struct {
|
||||
loc: Loc,
|
||||
kind: Kind,
|
||||
/// Filled in by Sema: the expression's type (a sema TypeId; 0 is the
|
||||
/// error type) and an index into Sema's per-expression information.
|
||||
ty: u32 = 0,
|
||||
info: u32 = 0,
|
||||
|
||||
pub const Kind = union(enum) {
|
||||
int_lit: []const u8,
|
||||
|
|
@ -154,6 +165,8 @@ pub const Expr = struct {
|
|||
init_list: []const *Expr,
|
||||
sizeof_type: *TypeRef,
|
||||
sizeof_expr: *Expr,
|
||||
/// `std::is_same<A, B>::value` (a dxc builtin).
|
||||
is_same: struct { a: *TypeRef, b: *TypeRef },
|
||||
};
|
||||
};
|
||||
|
||||
|
|
@ -190,6 +203,8 @@ pub const VarDecl = struct {
|
|||
/// Qualified out-of-line definitions (`int S::x = 1;`) keep the full
|
||||
/// spelled name, e.g. `S::x`.
|
||||
quals: Qualifiers,
|
||||
/// The qualifiers in source order.
|
||||
qual_words: []const QualWord = &.{},
|
||||
type: *TypeRef,
|
||||
name: []const u8,
|
||||
name_loc: Loc,
|
||||
|
|
@ -210,6 +225,7 @@ pub const TemplateParam = struct {
|
|||
pub const FuncDecl = struct {
|
||||
attrs: []const Attribute,
|
||||
quals: Qualifiers,
|
||||
qual_words: []const QualWord = &.{},
|
||||
template_params: []const TemplateParam,
|
||||
ret: *TypeRef,
|
||||
/// Function name; for operators `operator+`, `operator[]`, `operator()`.
|
||||
|
|
@ -258,7 +274,7 @@ 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 = &.{} },
|
||||
typedef: struct { name: []const u8, type: *TypeRef, array_dims: []const ?*Expr, template_params: []const TemplateParam = &.{}, qual_words: []const QualWord = &.{} },
|
||||
@"enum": EnumDecl,
|
||||
namespace: struct { name: []const u8, decls: []const *Decl },
|
||||
/// `using namespace N;`
|
||||
|
|
|
|||
|
|
@ -37,6 +37,11 @@ fn templateArgs(w: *W, args: []const ast.TemplateArg) W.Error!void {
|
|||
|
||||
pub fn typeRef(w: *W, t: *const ast.TypeRef) W.Error!void {
|
||||
if (t.norm != .none) try w.print("{s} ", .{@tagName(t.norm)});
|
||||
if (t.decltype) |e| {
|
||||
try w.writeAll("__decltype(");
|
||||
try expr(w, e);
|
||||
return w.writeByte(')');
|
||||
}
|
||||
try name(w, t.name);
|
||||
if (t.args.len > 0) try templateArgs(w, t.args);
|
||||
try dims(w, t.array_dims);
|
||||
|
|
@ -216,7 +221,7 @@ pub fn decl(w: *W, d: *const ast.Decl, depth: usize) W.Error!void {
|
|||
},
|
||||
.pragma => |p| try w.print("(pragma {s})", .{p}),
|
||||
.static_assert => |s| {
|
||||
try w.writeAll("(static_assert ");
|
||||
try w.writeAll("(_Static_assert ");
|
||||
try expr(w, s.cond);
|
||||
try w.writeByte(')');
|
||||
},
|
||||
|
|
@ -405,6 +410,13 @@ pub fn expr(w: *W, e: *const ast.Expr) W.Error!void {
|
|||
try typeRef(w, t);
|
||||
try w.writeByte(')');
|
||||
},
|
||||
.is_same => |x| {
|
||||
try w.writeAll("(is_same ");
|
||||
try typeRef(w, x.a);
|
||||
try w.writeAll(", ");
|
||||
try typeRef(w, x.b);
|
||||
try w.writeByte(')');
|
||||
},
|
||||
.sizeof_expr => |x| {
|
||||
try w.writeAll("(sizeof ");
|
||||
try expr(w, x);
|
||||
|
|
|
|||
|
|
@ -305,7 +305,8 @@ pub const Lexer = struct {
|
|||
}
|
||||
break;
|
||||
}
|
||||
if (isIdentChar(c) or c == '.') {
|
||||
// dxc also takes '#' (for `1.#INF`).
|
||||
if (isIdentChar(c) or c == '.' or c == '#') {
|
||||
l.pos += 1;
|
||||
continue;
|
||||
}
|
||||
|
|
@ -342,6 +343,7 @@ test "punctuators and literals" {
|
|||
try expectKinds("a+=b<<=c>>1.5e-3f", &.{ .identifier, .plus_equal, .identifier, .less_less_equal, .identifier, .greater_greater, .number });
|
||||
try expectKinds("x::y->z...", &.{ .identifier, .colon_colon, .identifier, .arrow, .identifier, .ellipsis });
|
||||
try expectKinds("\"a\\\"b\" 'c' .5h 0x1Fu", &.{ .string, .char, .number, .number });
|
||||
try expectKinds("1.#INF.xxx -1.#INF", &.{ .number, .minus, .number });
|
||||
try expectKinds("# ## #x", &.{ .hash, .hash_hash, .hash, .identifier });
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -35,6 +35,10 @@ pub const Parser = struct {
|
|||
/// Name of the struct most recently parsed by parseStructDeclInto
|
||||
/// (synthesized for anonymous structs), for `typedef struct ...`.
|
||||
last_struct_name: []const u8 = "",
|
||||
/// The qualifier words read by the last parseQualifiers call.
|
||||
last_quals: []const ast.QualWord = &.{},
|
||||
/// Qualifier words for the next parseDeclaratorsInto call.
|
||||
decl_quals: []const ast.QualWord = &.{},
|
||||
/// Set while parsing template arguments: a top-level `>` ends the
|
||||
/// argument instead of being a comparison.
|
||||
no_greater: bool = false,
|
||||
|
|
@ -295,6 +299,9 @@ pub const Parser = struct {
|
|||
if (p.toks[i].kind == .identifier and isBuiltinType(p.toks[i].text)) i += 1;
|
||||
return i;
|
||||
}
|
||||
if (p.toks[i].isIdent("__decltype") and p.toks[i + 1].kind == .l_paren) {
|
||||
return p.skipTypeAttrs(p.skipParens(i + 1) orelse return null);
|
||||
}
|
||||
if (p.toks[i].kind == .colon_colon) i += 1;
|
||||
while (true) {
|
||||
const t = p.toks[i];
|
||||
|
|
@ -347,6 +354,23 @@ pub const Parser = struct {
|
|||
}
|
||||
}
|
||||
|
||||
/// Index just past the `)` matching the `(` at `start`, or null.
|
||||
fn skipParens(p: *const Parser, start: usize) ?usize {
|
||||
var i = start;
|
||||
var depth: u32 = 0;
|
||||
while (true) : (i += 1) {
|
||||
switch (p.toks[i].kind) {
|
||||
.l_paren => depth += 1,
|
||||
.r_paren => {
|
||||
depth -= 1;
|
||||
if (depth == 0) return i + 1;
|
||||
},
|
||||
.semi, .l_brace, .r_brace, .eof => return null,
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Index just past the `>` matching the `<` at `i`, or null.
|
||||
fn skipAngles(p: *const Parser, start: usize) ?usize {
|
||||
var i = start;
|
||||
|
|
@ -425,6 +449,8 @@ pub const Parser = struct {
|
|||
/// `line`, ...) count only when a type or another qualifier follows.
|
||||
fn parseQualifiers(p: *Parser) ast.Qualifiers {
|
||||
var q: ast.Qualifiers = .{};
|
||||
var words: std.ArrayList(ast.QualWord) = .empty;
|
||||
defer p.last_quals = words.items;
|
||||
while (p.at(.identifier)) {
|
||||
const word = p.tok().text;
|
||||
const field = qualifierField(word) orelse break;
|
||||
|
|
@ -433,6 +459,7 @@ pub const Parser = struct {
|
|||
const next_is_qual = n.kind == .identifier and qualifierField(n.text) != null;
|
||||
if (!next_is_qual and !p.isTypeStartAt(p.pos + 1)) break;
|
||||
}
|
||||
words.append(p.arena, .{ .loc = p.tok().loc, .word = word }) catch {};
|
||||
_ = p.advance();
|
||||
if (std.mem.eql(u8, word, "inout")) {
|
||||
q.in = true;
|
||||
|
|
@ -465,6 +492,16 @@ pub const Parser = struct {
|
|||
const n = try p.parseNameWithFinalArgs();
|
||||
return p.mk(ast.TypeRef, .{ .loc = start.loc, .name = n.name, .args = n.args });
|
||||
}
|
||||
if (p.atIdent("__decltype")) {
|
||||
_ = p.advance();
|
||||
_ = try p.expect(.l_paren, "'('");
|
||||
const saved = p.no_greater;
|
||||
p.no_greater = false;
|
||||
const e = try p.parseExpr();
|
||||
p.no_greater = saved;
|
||||
_ = try p.expect(.r_paren, "')'");
|
||||
return p.mk(ast.TypeRef, .{ .loc = start.loc, .name = try p.simpleName(start.loc, "__decltype"), .decltype = e });
|
||||
}
|
||||
if (p.atIdent("unsigned") or p.atIdent("signed")) {
|
||||
const signed = p.advance().isIdent("signed");
|
||||
var base: []const u8 = "int";
|
||||
|
|
@ -663,14 +700,16 @@ pub const Parser = struct {
|
|||
if (t.isIdent("using")) return out.append(p.arena, try p.parseUsing(template_params));
|
||||
if (t.isIdent("namespace")) return out.append(p.arena, try p.parseNamespace());
|
||||
if (t.isIdent("enum")) return p.parseEnumInto(out);
|
||||
if (t.isIdent("static_assert")) {
|
||||
if (t.isIdent("_Static_assert")) {
|
||||
const d = try p.parseStaticAssert();
|
||||
_ = try p.expect(.semi, "';'");
|
||||
return out.append(p.arena, d);
|
||||
}
|
||||
|
||||
const quals = p.parseQualifiers();
|
||||
const words = p.last_quals;
|
||||
const ty = try p.parseType();
|
||||
p.decl_quals = words;
|
||||
try p.parseDeclaratorsInto(out, attrs, quals, template_params, ty, ctx);
|
||||
}
|
||||
|
||||
|
|
@ -848,6 +887,7 @@ pub const Parser = struct {
|
|||
fn parseTypedefInto(p: *Parser, out: *std.ArrayList(*ast.Decl)) Error!void {
|
||||
const kw = p.advance();
|
||||
_ = p.parseQualifiers();
|
||||
const words = p.last_quals;
|
||||
var ty: *ast.TypeRef = undefined;
|
||||
if (p.atIdent("struct") or p.atIdent("class")) {
|
||||
// `typedef struct { ... } Name;`
|
||||
|
|
@ -858,7 +898,7 @@ pub const Parser = struct {
|
|||
const name = try p.expectIdent("typedef name");
|
||||
const dims = try p.parseArrayDims();
|
||||
try p.declareName(name.text, .type);
|
||||
try out.append(p.arena, try p.mk(ast.Decl, .{ .loc = kw.loc, .kind = .{ .typedef = .{ .name = name.text, .type = ty, .array_dims = dims } } }));
|
||||
try out.append(p.arena, try p.mk(ast.Decl, .{ .loc = kw.loc, .kind = .{ .typedef = .{ .name = name.text, .type = ty, .array_dims = dims, .qual_words = words } } }));
|
||||
if (!p.eat(.comma)) break;
|
||||
}
|
||||
_ = try p.expect(.semi, "';'");
|
||||
|
|
@ -935,14 +975,17 @@ pub const Parser = struct {
|
|||
try p.parseDeclaratorsInto(out, &.{}, .{}, &.{}, ty, .global);
|
||||
}
|
||||
|
||||
/// `_Static_assert(cond, "message")`: C11's spelling, accepted by dxc in
|
||||
/// every language version (`static_assert` is an identifier in 2021).
|
||||
fn parseStaticAssert(p: *Parser) Error!*ast.Decl {
|
||||
// Parsed for recovery, but not part of HLSL 2021 (dxc rejects it).
|
||||
_ = p.reportAt(p.pos, .@"error", "'static_assert' requires HLSL 202x; zdxc implements HLSL 2021", .{});
|
||||
const kw = p.advance();
|
||||
_ = try p.expect(.l_paren, "'('");
|
||||
const cond = try p.parseAssign();
|
||||
var message: ?[]const u8 = null;
|
||||
if (p.eat(.comma)) message = (try p.expect(.string, "string literal")).text;
|
||||
if (p.eat(.comma)) {
|
||||
if (!p.at(.string)) return p.fail("expected string literal", .{});
|
||||
message = (try p.parsePrimary()).kind.string_lit; // adjacent literals concatenate
|
||||
}
|
||||
_ = try p.expect(.r_paren, "')'");
|
||||
return p.mk(ast.Decl, .{ .loc = kw.loc, .kind = .{ .static_assert = .{ .cond = cond, .message = message } } });
|
||||
}
|
||||
|
|
@ -957,6 +1000,8 @@ pub const Parser = struct {
|
|||
ty: *ast.TypeRef,
|
||||
ctx: DeclContext,
|
||||
) Error!void {
|
||||
const words = p.decl_quals;
|
||||
p.decl_quals = &.{};
|
||||
// Function names may be qualified (`S::method`) or operators;
|
||||
// variables may be qualified for out-of-line static members.
|
||||
const name_loc = p.tok().loc;
|
||||
|
|
@ -988,7 +1033,11 @@ pub const Parser = struct {
|
|||
} else p.pos = save;
|
||||
}
|
||||
}
|
||||
if (fname) |n| return out.append(p.arena, try p.parseFunctionRest(attrs, quals, template_params, ty, n, name_loc, ctx));
|
||||
if (fname) |n| {
|
||||
const d = try p.parseFunctionRest(attrs, quals, template_params, ty, n, name_loc, ctx);
|
||||
if (d.kind == .func) d.kind.func.qual_words = words;
|
||||
return out.append(p.arena, d);
|
||||
}
|
||||
|
||||
var first = true;
|
||||
while (true) {
|
||||
|
|
@ -1010,6 +1059,7 @@ pub const Parser = struct {
|
|||
.attrs = attrs,
|
||||
.template_params = template_params,
|
||||
.quals = quals,
|
||||
.qual_words = words,
|
||||
.type = ty,
|
||||
.name = name.text,
|
||||
.name_loc = name.loc,
|
||||
|
|
@ -1080,6 +1130,7 @@ pub const Parser = struct {
|
|||
while (!p.at(.r_paren)) {
|
||||
const pattrs = try p.parseAttributes();
|
||||
const pquals = p.parseQualifiers();
|
||||
const pwords = p.last_quals;
|
||||
const pty = try p.parseType();
|
||||
var pname: []const u8 = "";
|
||||
var pname_loc = p.tok().loc;
|
||||
|
|
@ -1097,6 +1148,7 @@ pub const Parser = struct {
|
|||
try params.append(p.arena, .{
|
||||
.attrs = pattrs,
|
||||
.quals = pquals,
|
||||
.qual_words = pwords,
|
||||
.type = pty,
|
||||
.name = pname,
|
||||
.name_loc = pname_loc,
|
||||
|
|
@ -1342,7 +1394,7 @@ pub const Parser = struct {
|
|||
if (t.kind == .identifier) {
|
||||
const w = t.text;
|
||||
if (std.mem.eql(u8, w, "struct") or std.mem.eql(u8, w, "class") or std.mem.eql(u8, w, "typedef") or
|
||||
std.mem.eql(u8, w, "using") or std.mem.eql(u8, w, "enum") or std.mem.eql(u8, w, "static_assert"))
|
||||
std.mem.eql(u8, w, "using") or std.mem.eql(u8, w, "enum") or std.mem.eql(u8, w, "_Static_assert"))
|
||||
return true;
|
||||
if (qualifierField(w) != null) {
|
||||
if (!isContextualQualifier(w)) return true;
|
||||
|
|
@ -1579,6 +1631,12 @@ pub const Parser = struct {
|
|||
switch (t.kind) {
|
||||
.number => {
|
||||
_ = p.advance();
|
||||
// HLSL allows swizzles on literals (`0x04.xxx`, `1.0.xxxx`);
|
||||
// the lexer reads them as one pp-number.
|
||||
if (splitLiteralSwizzle(t.text)) |split| {
|
||||
const lit = try p.mkExpr(t.loc, if (isFloatLiteral(split.literal)) .{ .float_lit = split.literal } else .{ .int_lit = split.literal });
|
||||
return p.mkExpr(t.loc, .{ .member = .{ .base = lit, .name = split.swizzle, .name_loc = t.loc.advance(@intCast(split.literal.len + 1)) } });
|
||||
}
|
||||
return p.mkExpr(t.loc, if (isFloatLiteral(t.text)) .{ .float_lit = t.text } else .{ .int_lit = t.text });
|
||||
},
|
||||
.string => {
|
||||
|
|
@ -1616,6 +1674,16 @@ pub const Parser = struct {
|
|||
_ = p.advance();
|
||||
return p.mkExpr(t.loc, .this);
|
||||
}
|
||||
if (t.isIdent("std") and p.peek(1).kind == .colon_colon and p.peek(2).isIdent("is_same") and p.peek(3).kind == .less) {
|
||||
p.pos += 3;
|
||||
const args = try p.parseTemplateArgs();
|
||||
_ = try p.expect(.colon_colon, "'::'");
|
||||
const v = try p.expect(.identifier, "'value'");
|
||||
if (args.len != 2 or args[0] != .type or args[1] != .type or !v.isIdent("value")) {
|
||||
return p.fail("expected 'std::is_same<type, type>::value'", .{});
|
||||
}
|
||||
return p.mkExpr(t.loc, .{ .is_same = .{ .a = args[0].type, .b = args[1].type } });
|
||||
}
|
||||
if (t.kind == .identifier and isReserved(t.text)) {
|
||||
return p.fail("expected expression, found '{s}'", .{t.text});
|
||||
}
|
||||
|
|
@ -1652,6 +1720,22 @@ fn describe(t: Token) []const u8 {
|
|||
return if (t.kind == .eof) "end of file" else t.text;
|
||||
}
|
||||
|
||||
/// `0x04.xxx` -> literal `0x04`, swizzle `xxx`; `1.0.xy` -> `1.0`, `xy`.
|
||||
fn splitLiteralSwizzle(text: []const u8) ?struct { literal: []const u8, swizzle: []const u8 } {
|
||||
const dot = std.mem.lastIndexOfScalar(u8, text, '.') orelse return null;
|
||||
const sw = text[dot + 1 ..];
|
||||
if (sw.len == 0 or sw.len > 4) return null;
|
||||
for (sw) |c| if (std.mem.indexOfScalar(u8, "xyzwrgba", c) == null) return null;
|
||||
const lit = text[0..dot];
|
||||
if (lit.len == 0) return null;
|
||||
// `1.xx`: the literal must not end in an exponent marker.
|
||||
if (std.ascii.isAlphabetic(lit[lit.len - 1]) and !(lit.len > 1 and lit[0] == '0' and (lit[1] == 'x' or lit[1] == 'X'))) {
|
||||
const last = lit[lit.len - 1];
|
||||
if (last != 'f' and last != 'F' and last != 'h' and last != 'H' and last != 'u' and last != 'U' and last != 'l' and last != 'L') return null;
|
||||
}
|
||||
return .{ .literal = lit, .swizzle = sw };
|
||||
}
|
||||
|
||||
fn isFloatLiteral(text: []const u8) bool {
|
||||
if (text.len > 1 and text[0] == '0' and (text[1] == 'x' or text[1] == 'X')) return false;
|
||||
if (std.mem.indexOfAny(u8, text, ".eE") != null) return true;
|
||||
|
|
@ -1660,14 +1744,7 @@ fn isFloatLiteral(text: []const u8) bool {
|
|||
}
|
||||
|
||||
/// Words that can never be identifiers.
|
||||
const reserved_words = [_][]const u8{
|
||||
"if", "else", "for", "while", "do", "switch", "case",
|
||||
"default", "break", "continue", "return", "discard", "struct", "class",
|
||||
"interface", "cbuffer", "tbuffer", "typedef", "namespace", "enum", "template",
|
||||
"typename", "true", "false", "this", "sizeof", "static", "const",
|
||||
"uniform", "extern", "volatile", "groupshared", "inline", "using", "operator",
|
||||
"static_assert", "inout", "in", "out",
|
||||
};
|
||||
const reserved_words = [_][]const u8{ "if", "else", "for", "while", "do", "switch", "case", "default", "break", "continue", "return", "discard", "struct", "class", "interface", "cbuffer", "tbuffer", "typedef", "namespace", "enum", "template", "typename", "true", "false", "this", "sizeof", "static", "const", "uniform", "extern", "volatile", "groupshared", "inline", "using", "operator", "_Static_assert", "inout", "in", "out", "__decltype" };
|
||||
|
||||
/// Qualifier keywords and their ast.Qualifiers field names.
|
||||
const qualifier_words = [_][2][]const u8{
|
||||
|
|
@ -1681,7 +1758,7 @@ const qualifier_words = [_][2][]const u8{
|
|||
.{ "export", "export" }, .{ "point", "point" }, .{ "line", "line" },
|
||||
.{ "triangle", "triangle" }, .{ "lineadj", "lineadj" }, .{ "triangleadj", "triangleadj" },
|
||||
.{ "vertices", "vertices" }, .{ "indices", "indices" }, .{ "primitives", "primitives" },
|
||||
.{ "payload", "payload" },
|
||||
.{ "payload", "payload" }, .{ "center", "center" },
|
||||
};
|
||||
|
||||
/// Qualifiers that are ordinary identifiers unless a type follows.
|
||||
|
|
@ -1689,6 +1766,7 @@ const contextual_words = [_][]const u8{
|
|||
"precise", "shared", "row_major", "column_major", "nointerpolation", "linear", "centroid",
|
||||
"sample", "noperspective", "globallycoherent", "reordercoherent", "export", "point", "line",
|
||||
"triangle", "lineadj", "triangleadj", "vertices", "indices", "primitives", "payload",
|
||||
"center",
|
||||
};
|
||||
|
||||
fn isReserved(w: []const u8) bool {
|
||||
|
|
|
|||
34
src/main.zig
34
src/main.zig
|
|
@ -29,6 +29,7 @@ const Options = struct {
|
|||
error_limit: u32 = 20,
|
||||
parse: bool = false,
|
||||
dump_ast: bool = false,
|
||||
sema: bool = false,
|
||||
/// -O0..-O3 / -Od (default -O3, as in dxc).
|
||||
opt_level: enum { od, o0, o1, o2, o3 } = .o3,
|
||||
/// Accepted options with no effect yet, reported once each.
|
||||
|
|
@ -91,6 +92,7 @@ fn parseArgs(cli: Cli, arena: std.mem.Allocator, argv: []const [:0]const u8, std
|
|||
opts.parse = true;
|
||||
opts.dump_ast = true;
|
||||
},
|
||||
.zdxc_sema => opts.sema = true,
|
||||
.fcolor_diagnostics => opts.color = true,
|
||||
.fno_color_diagnostics => opts.color = false,
|
||||
},
|
||||
|
|
@ -211,7 +213,9 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
|
|||
else
|
||||
null;
|
||||
|
||||
if (opts.preprocess or opts.parse) {
|
||||
// The front end: everything except the development modes that work on
|
||||
// containers or raw tokens.
|
||||
if (!opts.empty) {
|
||||
const input = opts.input orelse return cli.fail("no input file", .{});
|
||||
var disk: front.source.DiskFs = .{ .io = cli.io };
|
||||
var sm = front.source.SourceManager.init(arena, disk.fileSystem());
|
||||
|
|
@ -231,20 +235,36 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
|
|||
});
|
||||
var out: Io.Writer.Allocating = .init(arena);
|
||||
if (try pp.enterMainFile(input)) {
|
||||
if (opts.parse) {
|
||||
if (opts.preprocess) {
|
||||
try front.pp_print.print(&pp, &out.writer);
|
||||
} else {
|
||||
var parser = try front.parser.Parser.fromPreprocessor(arena, &diags, &pp);
|
||||
const tu = try parser.parseTranslationUnit();
|
||||
if (opts.dump_ast) try front.ast_dump.dumpUnit(stdout, tu);
|
||||
} else try front.pp_print.print(&pp, &out.writer);
|
||||
if (!opts.parse) {
|
||||
const is_lib = if (profile) |p| p.kind == .library else true;
|
||||
var sema = try zdxc.sema.Sema.init(arena, &diags, .{
|
||||
.entry = if (opts.sema or is_lib) null else opts.entry,
|
||||
.spirv = opts.spirv,
|
||||
.enable_16bit = opts.enable_16bit,
|
||||
});
|
||||
try sema.checkUnit(tu);
|
||||
}
|
||||
}
|
||||
}
|
||||
const color = opts.color orelse (Io.File.stderr().supportsAnsiEscapeCodes(cli.io) catch false);
|
||||
try diags.render(&sm, cli.stderr, .{ .format = opts.diag_format, .color = color });
|
||||
try cli.stderr.flush();
|
||||
if (diags.hasErrors()) return error.CompileFailed;
|
||||
if (opts.pp_output) |path| {
|
||||
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = path, .data = out.written() });
|
||||
} else try stdout.writeAll(out.written());
|
||||
return;
|
||||
if (opts.preprocess) {
|
||||
if (opts.pp_output) |path| {
|
||||
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = path, .data = out.written() });
|
||||
} else try stdout.writeAll(out.written());
|
||||
return;
|
||||
}
|
||||
if (opts.parse or opts.sema) return;
|
||||
if (profile == null) return cli.fail("missing -T <profile>", .{});
|
||||
return cli.fail("code generation is not implemented yet: the input was checked but no output was written (use -zdxc-empty for a placeholder shader)", .{});
|
||||
}
|
||||
|
||||
const prof = profile orelse return cli.fail("missing -T <profile>", .{});
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ pub const Extra = enum {
|
|||
zdxc_lex,
|
||||
zdxc_parse,
|
||||
zdxc_ast,
|
||||
zdxc_sema,
|
||||
fcolor_diagnostics,
|
||||
fno_color_diagnostics,
|
||||
};
|
||||
|
|
@ -37,6 +38,7 @@ const extra_options = [_]struct { id: Extra, spelling: []const u8, help: []const
|
|||
.{ .id = .zdxc_lex, .spelling = "zdxc-lex", .help = "Print the input's tokens, one per line (development)" },
|
||||
.{ .id = .zdxc_parse, .spelling = "zdxc-parse", .help = "Preprocess and parse the input, reporting syntax errors only (development)" },
|
||||
.{ .id = .zdxc_ast, .spelling = "zdxc-ast", .help = "Preprocess, parse and dump the syntax tree (development)" },
|
||||
.{ .id = .zdxc_sema, .spelling = "zdxc-sema", .help = "Run the front end through semantic analysis only (development)" },
|
||||
.{ .id = .fcolor_diagnostics, .spelling = "fcolor-diagnostics", .help = "Always use colors in diagnostics" },
|
||||
.{ .id = .fno_color_diagnostics, .spelling = "fno-color-diagnostics", .help = "Never use colors in diagnostics" },
|
||||
};
|
||||
|
|
|
|||
|
|
@ -23,6 +23,12 @@ pub const dxil = struct {
|
|||
pub const shader = @import("dxil/shader.zig");
|
||||
};
|
||||
|
||||
pub const sema = struct {
|
||||
pub const types = @import("sema/types.zig");
|
||||
pub const intrinsics = @import("sema/intrinsics.zig");
|
||||
pub const Sema = @import("sema/sema.zig").Sema;
|
||||
};
|
||||
|
||||
pub const spirv = struct {
|
||||
pub const builder = @import("spirv/builder.zig");
|
||||
};
|
||||
|
|
@ -33,6 +39,8 @@ test {
|
|||
const std = @import("std");
|
||||
std.testing.refAllDecls(front);
|
||||
std.testing.refAllDecls(dxil);
|
||||
_ = @import("sema/types.zig");
|
||||
_ = @import("sema/sema.zig");
|
||||
std.testing.refAllDecls(spirv);
|
||||
_ = @import("diag.zig");
|
||||
_ = @import("options.zig");
|
||||
|
|
|
|||
|
|
@ -0,0 +1,367 @@
|
|||
//! Intrinsic and builtin-method overload resolution against the table
|
||||
//! generated from dxc's gen_intrin_main.txt.
|
||||
//!
|
||||
//! Each declaration's types are indexed 0 (return) .. n (parameters).
|
||||
//! `$match<L, C>` links a type's layout to type L and its component to
|
||||
//! type C (`$typeN` = `$match<N, N>`); unlinked types are their own group.
|
||||
//! For each group the component is the common type of its arguments,
|
||||
//! coerced into the group's class (`float_like`, `numeric`, `any_int`...),
|
||||
//! and the layout is taken from the declared dimensions (binding symbolic
|
||||
//! sizes like `c` and `r2` across arguments) or, for `<>`, from the
|
||||
//! arguments. Candidates are ranked by total conversion cost.
|
||||
|
||||
const std = @import("std");
|
||||
const Allocator = std.mem.Allocator;
|
||||
const table = @import("intrinsics_table");
|
||||
const types = @import("types.zig");
|
||||
const source = @import("../front/source.zig");
|
||||
const TypeId = types.TypeId;
|
||||
const TypeTable = types.TypeTable;
|
||||
const Scalar = types.Scalar;
|
||||
|
||||
pub const ArgInfo = struct {
|
||||
ty: TypeId,
|
||||
/// Assignable (for out / inout parameters).
|
||||
lvalue: bool,
|
||||
loc: source.Loc,
|
||||
/// Names (part of) a groupshared variable.
|
||||
groupshared: bool = false,
|
||||
};
|
||||
|
||||
pub const Db = struct {
|
||||
/// "Namespace::name" -> indices into table.intrinsics.
|
||||
by_name: std.StringHashMapUnmanaged(std.ArrayList(u16)) = .empty,
|
||||
/// Plain intrinsic names (Intrinsics / VkIntrinsics / DxIntrinsics).
|
||||
globals: std.StringHashMapUnmanaged(void) = .empty,
|
||||
vk_globals: std.StringHashMapUnmanaged(void) = .empty,
|
||||
|
||||
pub fn init(a: Allocator) !Db {
|
||||
var db: Db = .{};
|
||||
for (table.intrinsics, 0..) |it, i| {
|
||||
const key = try std.fmt.allocPrint(a, "{s}::{s}", .{ it.namespace, it.name });
|
||||
const gop = try db.by_name.getOrPut(a, key);
|
||||
if (!gop.found_existing) gop.value_ptr.* = .empty;
|
||||
try gop.value_ptr.append(a, @intCast(i));
|
||||
if (std.mem.eql(u8, it.namespace, "Intrinsics") or std.mem.eql(u8, it.namespace, "DxIntrinsics")) try db.globals.put(a, it.name, {});
|
||||
if (std.mem.eql(u8, it.namespace, "VkIntrinsics")) try db.vk_globals.put(a, it.name, {});
|
||||
}
|
||||
return db;
|
||||
}
|
||||
|
||||
pub fn has(db: *const Db, name: []const u8, spirv: bool) bool {
|
||||
return db.globals.contains(name) or (spirv and db.vk_globals.contains(name));
|
||||
}
|
||||
|
||||
fn candidates(db: *const Db, a: Allocator, ns: []const u8, name: []const u8) ![]const u16 {
|
||||
var list: std.ArrayList(u16) = .empty;
|
||||
const namespaces: []const []const u8 = if (std.mem.eql(u8, ns, "Intrinsics")) &.{ "Intrinsics", "DxIntrinsics" } else &.{ns};
|
||||
for (namespaces) |n| {
|
||||
const key = try std.fmt.allocPrint(a, "{s}::{s}", .{ n, name });
|
||||
if (db.by_name.get(key)) |l| try list.appendSlice(a, l.items);
|
||||
}
|
||||
return list.items;
|
||||
}
|
||||
|
||||
/// Resolve a call; reports a diagnostic and returns the error type when
|
||||
/// no overload matches. `sema` is the calling Sema (for conversions and
|
||||
/// diagnostics); `object` is the method's object type, if any.
|
||||
pub fn resolve(db: *const Db, sema: anytype, loc: source.Loc, ns: []const u8, name: []const u8, object: ?TypeId, args: []const ArgInfo, explicit: ?TypeId) !TypeId {
|
||||
const cands = try db.candidates(sema.arena, ns, name);
|
||||
if (cands.len == 0) {
|
||||
if (object) |o| {
|
||||
sema.err(loc, "no member named '{s}' in '{s}'", .{ name, sema.typeName(o) });
|
||||
} else sema.err(loc, "use of undeclared identifier '{s}'", .{name});
|
||||
return TypeTable.error_type;
|
||||
}
|
||||
var best: ?Match = null;
|
||||
for (cands) |ci| {
|
||||
const m = try matchOne(sema, &table.intrinsics[ci], object, args, explicit) orelse continue;
|
||||
if (best == null or m.cost < best.?.cost) best = m;
|
||||
}
|
||||
// vk::static_pointer_cast / reinterpret_pointer_cast return a
|
||||
// BufferPointer of the template argument: not modelled yet.
|
||||
if (best != null and (std.mem.eql(u8, name, "static_pointer_cast") or std.mem.eql(u8, name, "reinterpret_pointer_cast"))) return TypeTable.error_type;
|
||||
const m = best orelse {
|
||||
sema.err(loc, "no matching function for call to '{s}'", .{name});
|
||||
return TypeTable.error_type;
|
||||
};
|
||||
for (args, 0..) |a, i| {
|
||||
if (i < m.out_params.len and m.out_params[i] and !a.lvalue) {
|
||||
sema.err(a.loc, "cannot bind non-lvalue argument to out parameter", .{});
|
||||
}
|
||||
}
|
||||
return m.ret;
|
||||
}
|
||||
};
|
||||
|
||||
const Match = struct {
|
||||
ret: TypeId,
|
||||
cost: u32,
|
||||
out_params: []const bool,
|
||||
};
|
||||
|
||||
const Layout = struct { rows: u8, cols: u8, kind: TypeTable.Shape };
|
||||
|
||||
/// Symbolic dimension bindings (`r`, `c`, `r2`, `c2`, ...).
|
||||
const Bindings = struct {
|
||||
names: [8][]const u8 = undefined,
|
||||
values: [8]u8 = undefined,
|
||||
n: usize = 0,
|
||||
|
||||
fn get(b: *const Bindings, name: []const u8) ?u8 {
|
||||
for (b.names[0..b.n], b.values[0..b.n]) |k, v| if (std.mem.eql(u8, k, name)) return v;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Bind or check; false on conflict.
|
||||
fn bind(b: *Bindings, name: []const u8, v: u8) bool {
|
||||
if (b.get(name)) |old| return old == v;
|
||||
if (b.n == b.names.len) return false;
|
||||
b.names[b.n] = name;
|
||||
b.values[b.n] = v;
|
||||
b.n += 1;
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
fn matchOne(sema: anytype, it: *const table.Intrinsic, object: ?TypeId, args: []const ArgInfo, explicit: ?TypeId) !?Match {
|
||||
const t = &sema.types;
|
||||
if (args.len < it.params.len) return null;
|
||||
if (args.len > it.params.len and !it.varargs) return null;
|
||||
const n = it.params.len + 1;
|
||||
const specs = try sema.arena.alloc(*const table.Spec, n);
|
||||
specs[0] = &it.ret;
|
||||
for (it.params, 1..) |*p, i| specs[i] = p;
|
||||
|
||||
const obj_elem: TypeId = if (object) |o| switch (t.get(o)) {
|
||||
.resource => |r| r.elem,
|
||||
.stream => |s| s.elem,
|
||||
.patch => |p| p.elem,
|
||||
else => TypeTable.error_type,
|
||||
} else TypeTable.error_type;
|
||||
|
||||
// Groups: index of the type that owns a type's layout / component.
|
||||
const comp_group = try sema.arena.alloc(usize, n);
|
||||
const layout_group = try sema.arena.alloc(usize, n);
|
||||
for (specs, 0..) |s, i| {
|
||||
comp_group[i] = i;
|
||||
layout_group[i] = i;
|
||||
if (s.special == .type_n) {
|
||||
comp_group[i] = s.type_n;
|
||||
layout_group[i] = s.type_n;
|
||||
} else {
|
||||
if (s.match_comp) |c| if (c >= 0 and c < n) {
|
||||
comp_group[i] = @intCast(c);
|
||||
};
|
||||
if (s.match_layout) |l| if (l >= 0 and l < n) {
|
||||
layout_group[i] = @intCast(l);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Components: common type of the arguments in each group.
|
||||
const group_comp = try sema.arena.alloc(?Scalar, n);
|
||||
@memset(group_comp, null);
|
||||
for (args[0..it.params.len], 1..) |a, i| {
|
||||
const g = comp_group[i];
|
||||
const c = t.component(a.ty) orelse continue;
|
||||
group_comp[g] = if (group_comp[g]) |old| common(old, c) else c;
|
||||
}
|
||||
|
||||
var bindings: Bindings = .{};
|
||||
var cost: u32 = 0;
|
||||
const out_params = try sema.arena.alloc(bool, args.len);
|
||||
@memset(out_params, false);
|
||||
|
||||
// Parameter types, checked against the arguments.
|
||||
for (args, 0..) |a, ai| {
|
||||
if (ai >= it.params.len) break; // varargs: anything goes
|
||||
const i = ai + 1;
|
||||
const s = specs[i];
|
||||
out_params[ai] = s.qual == .out or s.qual == .inout or s.qual == .ref;
|
||||
const pt = try paramType(sema, specs, i, comp_group, layout_group, group_comp, &bindings, args, obj_elem, explicit) orelse return null;
|
||||
if (pt == TypeTable.error_type) continue; // unconstrained object / unknown class
|
||||
const c = sema.conversionCost(a.ty, pt) orelse return null;
|
||||
cost += c;
|
||||
}
|
||||
|
||||
// Return type.
|
||||
const ret = try paramType(sema, specs, 0, comp_group, layout_group, group_comp, &bindings, args, obj_elem, explicit) orelse return null;
|
||||
return .{ .ret = ret, .cost = cost, .out_params = out_params };
|
||||
}
|
||||
|
||||
/// The concrete type of spec `i`, or null if the arguments cannot fit.
|
||||
/// Returns the error type for types zdxc does not constrain (objects,
|
||||
/// strings, classes it does not model).
|
||||
fn paramType(
|
||||
sema: anytype,
|
||||
specs: []const *const table.Spec,
|
||||
i: usize,
|
||||
comp_group: []const usize,
|
||||
layout_group: []const usize,
|
||||
group_comp: []const ?Scalar,
|
||||
bindings: *Bindings,
|
||||
args: []const ArgInfo,
|
||||
obj_elem: TypeId,
|
||||
explicit: ?TypeId,
|
||||
) !?TypeId {
|
||||
const t = &sema.types;
|
||||
const s = specs[i];
|
||||
switch (s.special) {
|
||||
.class_t => return obj_elem,
|
||||
// `$funcT`: the explicit template argument; without one, a return
|
||||
// defaults to uint (ByteAddressBuffer.Load) and a parameter is
|
||||
// unconstrained (Store of a struct).
|
||||
.func_t => return explicit orelse if (i == 0) try t.scalar(.uint) else TypeTable.error_type,
|
||||
else => {},
|
||||
}
|
||||
// Owner specs define the class and layout of linked types. `$match`
|
||||
// links the layout's kind; explicit dimensions on the spec itself win
|
||||
// (`$match<2, 2> float<2> ddx`, transpose's `any<c, r>`).
|
||||
const cs = specs[comp_group[i]];
|
||||
const ls = if (s.dims.len > 0) s else specs[layout_group[i]];
|
||||
|
||||
// Non-numeric classes.
|
||||
const base = if (cs.special == .none) cs.base else s.base;
|
||||
if (!std.mem.eql(u8, base, "void") and !isNumericClass(base)) {
|
||||
// Objects (samplers are checked) and classes zdxc does not model
|
||||
// (HitObject, node records, LinAlg...): unconstrained.
|
||||
if (i > 0 and i - 1 < args.len and isObjectClass(base)) return objectCheck(sema, base, args[i - 1].ty);
|
||||
return TypeTable.error_type;
|
||||
}
|
||||
if (isObjectClass(base)) {
|
||||
if (i > 0 and i - 1 < args.len) return objectCheck(sema, base, args[i - 1].ty);
|
||||
return TypeTable.error_type;
|
||||
}
|
||||
if (std.mem.eql(u8, base, "void")) {
|
||||
// `$match<0, -1> void<4>`: the object's component type.
|
||||
if (s.match_comp != null and s.match_comp.? == -1 and obj_elem != TypeTable.error_type) {
|
||||
const comp = t.component(obj_elem) orelse return TypeTable.error_type;
|
||||
return try layoutType(sema, ls, comp, layout_group[i], bindings, args);
|
||||
}
|
||||
if (s.match_layout != null and s.match_layout.? == -1) return obj_elem;
|
||||
return TypeTable.void_type;
|
||||
}
|
||||
|
||||
var comp = classComponent(base, group_comp[comp_group[i]]) orelse return null;
|
||||
if (comp.isLiteral()) comp = comp.concrete();
|
||||
return try layoutType(sema, ls, comp, layout_group[i], bindings, args);
|
||||
}
|
||||
|
||||
fn layoutType(sema: anytype, ls: *const table.Spec, comp: Scalar, group: usize, bindings: *Bindings, args: []const ArgInfo) !?TypeId {
|
||||
const t = &sema.types;
|
||||
if (ls.any_layout) {
|
||||
// `<>`: the shape of the group's arguments (scalars splat to the
|
||||
// widest one).
|
||||
var shape: ?TypeTable.Shape = null;
|
||||
if (group > 0 and group - 1 < args.len) shape = t.shape(args[group - 1].ty);
|
||||
if (shape == null) {
|
||||
// Look for any argument in this layout group.
|
||||
return try t.scalar(comp);
|
||||
}
|
||||
return try t.withShape(comp, shape.?);
|
||||
}
|
||||
if (ls.dims.len == 0) return try t.scalar(comp);
|
||||
const arg_shape: ?TypeTable.Shape = if (group > 0 and group - 1 < args.len) t.shape(args[group - 1].ty) else null;
|
||||
if (ls.dims.len == 1) {
|
||||
const len = dimValue(ls.dims[0], bindings, if (arg_shape) |sh| (if (sh.kind == .vector) sh.cols else if (sh.kind == .scalar) 1 else sh.cols) else null) orelse return null;
|
||||
if (len < 1 or len > 4) return null;
|
||||
return try t.vector(comp, len);
|
||||
}
|
||||
const rows = dimValue(ls.dims[0], bindings, if (arg_shape) |sh| sh.rows else null) orelse return null;
|
||||
const cols = dimValue(ls.dims[1], bindings, if (arg_shape) |sh| sh.cols else null) orelse return null;
|
||||
if (rows < 1 or rows > 4 or cols < 1 or cols > 4) return null;
|
||||
return try t.matrix(comp, rows, cols);
|
||||
}
|
||||
|
||||
/// A layout dimension: a number, or a symbol bound from the argument.
|
||||
fn dimValue(dim: []const u8, b: *Bindings, from_arg: ?u8) ?u8 {
|
||||
if (std.fmt.parseInt(u8, dim, 10)) |v| return v else |_| {}
|
||||
if (b.get(dim)) |v| return v;
|
||||
const v = from_arg orelse return null;
|
||||
if (!b.bind(dim, v)) return null;
|
||||
return v;
|
||||
}
|
||||
|
||||
fn common(a: Scalar, b: Scalar) Scalar {
|
||||
return Scalar.combine(a, b);
|
||||
}
|
||||
|
||||
/// The component a class gives for argument component `c` (null: no
|
||||
/// argument decided it). Concrete classes ignore the arguments.
|
||||
fn classComponent(base: []const u8, c: ?Scalar) ?Scalar {
|
||||
const fixed = [_]struct { []const u8, Scalar }{
|
||||
.{ "bool", .bool }, .{ "int", .int }, .{ "uint", .uint }, .{ "float", .float },
|
||||
.{ "double", .double }, .{ "u64", .uint64 }, .{ "i64", .int64 }, .{ "int16_t", .int16 },
|
||||
.{ "uint16_t", .uint16 }, .{ "float16_t", .float16 }, .{ "half", .half }, .{ "int64_t", .int64 },
|
||||
.{ "uint64_t", .uint64 }, .{ "uint_only", .uint }, .{ "int32_only", .int }, .{ "int64_only", .int64 },
|
||||
.{ "any_int32", .int }, .{ "any_int64", .int64 }, .{ "uint_only32", .uint }, .{ "p32i8", .uint },
|
||||
.{ "p32u8", .uint }, .{ "int8_t4_packed", .int8_4packed }, .{ "uint8_t4_packed", .uint8_4packed },
|
||||
};
|
||||
for (fixed) |f| {
|
||||
if (std.mem.eql(u8, f[0], base)) {
|
||||
// Classes that only fix the width keep the argument's type
|
||||
// when it fits (int32_only accepts int and uint).
|
||||
if (c) |arg| {
|
||||
if (std.mem.eql(u8, base, "int32_only") or std.mem.eql(u8, base, "any_int32") or std.mem.eql(u8, base, "uint_only")) {
|
||||
if (arg.isInt() and arg.size() == 4) return arg.concrete();
|
||||
}
|
||||
if (std.mem.eql(u8, base, "int64_only") or std.mem.eql(u8, base, "any_int64")) {
|
||||
if (arg.isInt() and arg.size() == 8) return arg;
|
||||
}
|
||||
}
|
||||
return f[1];
|
||||
}
|
||||
}
|
||||
const arg = c orelse return switch (base.len) {
|
||||
else => if (std.mem.eql(u8, base, "float_like") or std.mem.eql(u8, base, "any_float")) Scalar.float else Scalar.int,
|
||||
};
|
||||
if (std.mem.eql(u8, base, "float_like") or std.mem.eql(u8, base, "any_float") or std.mem.eql(u8, base, "float32_only") or std.mem.eql(u8, base, "fldbl") or std.mem.eql(u8, base, "float_like16")) {
|
||||
return if (arg.isFloat()) arg.concrete() else .float;
|
||||
}
|
||||
if (std.mem.eql(u8, base, "any_int") or std.mem.eql(u8, base, "any_int16or32") or std.mem.eql(u8, base, "sint16or32_only") or std.mem.eql(u8, base, "int16_only")) {
|
||||
return if (arg.isInt()) arg.concrete() else .int;
|
||||
}
|
||||
if (std.mem.eql(u8, base, "numeric32_only")) return if (arg.size() == 4 and arg != .bool) arg.concrete() else if (arg.isFloat()) .float else .int;
|
||||
if (std.mem.eql(u8, base, "numeric16_only")) return if (arg.size() == 2) arg else .int16;
|
||||
if (std.mem.eql(u8, base, "numeric")) return if (arg == .bool) .int else arg.concrete();
|
||||
// any, any_sampler... and unmodelled classes: keep the argument's type.
|
||||
return arg.concrete();
|
||||
}
|
||||
|
||||
/// Component classes that denote numeric types.
|
||||
fn isNumericClass(base: []const u8) bool {
|
||||
const names = [_][]const u8{
|
||||
"bool", "int", "uint", "float", "double", "u64", "i64",
|
||||
"int16_t", "uint16_t", "float16_t", "half", "int64_t", "uint64_t", "uint_only",
|
||||
"int32_only", "int64_only", "any_int32", "any_int64", "uint_only32", "p32i8", "p32u8",
|
||||
"int8_t4_packed", "uint8_t4_packed", "float_like", "any_float", "float32_only", "fldbl", "float_like16",
|
||||
"any_int", "any_int16or32", "sint16or32_only", "int16_only", "numeric32_only", "numeric16_only", "numeric",
|
||||
"any", "float16_t_only", "float32_t_only", "int16_t_only", "uint16_t_only",
|
||||
};
|
||||
for (names) |k| if (std.mem.eql(u8, k, base)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
fn isObjectClass(base: []const u8) bool {
|
||||
const names = [_][]const u8{
|
||||
"sampler", "sampler_cmp", "any_sampler", "sampler1d", "sampler2d", "sampler3d", "sampler_cube", "string", "wave",
|
||||
"ray_desc", "acceleration_struct", "udt", "resource", "LinAlg", "LinAlgMatrix", "node_record_or_uav", "any_node_output_record", "Texture1D",
|
||||
"Texture2D", "Texture2DArray", "Texture3D", "TextureCube",
|
||||
};
|
||||
for (names) |k| if (std.mem.eql(u8, k, base)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Object parameters: check samplers; anything else is accepted.
|
||||
fn objectCheck(sema: anytype, base: []const u8, arg: TypeId) ?TypeId {
|
||||
const t = &sema.types;
|
||||
const ty = t.get(arg);
|
||||
if (std.mem.eql(u8, base, "sampler") or std.mem.eql(u8, base, "sampler_cmp") or std.mem.eql(u8, base, "any_sampler")) {
|
||||
if (ty != .sampler) return if (ty == .@"error") TypeTable.error_type else null;
|
||||
if (std.mem.eql(u8, base, "sampler_cmp") and !ty.sampler.comparison) return null;
|
||||
if (std.mem.eql(u8, base, "sampler") and ty.sampler.comparison) return null;
|
||||
return TypeTable.error_type;
|
||||
}
|
||||
return TypeTable.error_type;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,531 @@
|
|||
//! HLSL types, interned in a TypeTable so that type identity is an integer
|
||||
//! comparison.
|
||||
|
||||
const std = @import("std");
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
pub const TypeId = u32;
|
||||
|
||||
/// Scalar (component) types. `literal_*` are the types of unsuffixed
|
||||
/// literals, which adapt to the other operand as in dxc.
|
||||
pub const Scalar = enum(u8) {
|
||||
bool,
|
||||
int,
|
||||
uint,
|
||||
half,
|
||||
float,
|
||||
double,
|
||||
min16float,
|
||||
min10float,
|
||||
min16int,
|
||||
min12int,
|
||||
min16uint,
|
||||
int16,
|
||||
uint16,
|
||||
int64,
|
||||
uint64,
|
||||
float16,
|
||||
literal_int,
|
||||
literal_float,
|
||||
int8_4packed,
|
||||
uint8_4packed,
|
||||
|
||||
pub fn isFloat(s: Scalar) bool {
|
||||
return switch (s) {
|
||||
.half, .float, .double, .min16float, .min10float, .float16, .literal_float => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn isInt(s: Scalar) bool {
|
||||
return switch (s) {
|
||||
.int, .uint, .min16int, .min12int, .min16uint, .int16, .uint16, .int64, .uint64, .literal_int, .int8_4packed, .uint8_4packed => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn isUnsigned(s: Scalar) bool {
|
||||
return switch (s) {
|
||||
.uint, .min16uint, .uint16, .uint64, .uint8_4packed => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn isLiteral(s: Scalar) bool {
|
||||
return s == .literal_int or s == .literal_float;
|
||||
}
|
||||
|
||||
const Props = packed struct(u16) {
|
||||
boolean: bool = false,
|
||||
literal: bool = false,
|
||||
floating: bool = false,
|
||||
integer: bool = false,
|
||||
unsigned: bool = false,
|
||||
min_precision: bool = false,
|
||||
/// `half` without -enable-16bit-types (32-bit, partial precision).
|
||||
partial_precision: bool = false,
|
||||
_: u9 = 0,
|
||||
};
|
||||
|
||||
/// dxc's basic-kind properties (g_uBasicKindProps in SemaHLSL.cpp):
|
||||
/// bit width (0 for bool and literals) and flags.
|
||||
fn props(s: Scalar) struct { bits: u8, p: Props } {
|
||||
return switch (s) {
|
||||
.bool => .{ .bits = 0, .p = .{ .boolean = true, .integer = true } },
|
||||
.literal_float => .{ .bits = 0, .p = .{ .floating = true, .literal = true } },
|
||||
.literal_int => .{ .bits = 0, .p = .{ .integer = true, .literal = true } },
|
||||
.float16 => .{ .bits = 16, .p = .{ .floating = true } },
|
||||
.half => .{ .bits = 32, .p = .{ .floating = true, .partial_precision = true } },
|
||||
.float => .{ .bits = 32, .p = .{ .floating = true } },
|
||||
.double => .{ .bits = 64, .p = .{ .floating = true } },
|
||||
.int16 => .{ .bits = 16, .p = .{ .integer = true } },
|
||||
.uint16 => .{ .bits = 16, .p = .{ .integer = true, .unsigned = true } },
|
||||
.int => .{ .bits = 32, .p = .{ .integer = true } },
|
||||
.uint, .int8_4packed, .uint8_4packed => .{ .bits = 32, .p = .{ .integer = true, .unsigned = true } },
|
||||
.int64 => .{ .bits = 64, .p = .{ .integer = true } },
|
||||
.uint64 => .{ .bits = 64, .p = .{ .integer = true, .unsigned = true } },
|
||||
.min10float => .{ .bits = 10, .p = .{ .floating = true, .min_precision = true } },
|
||||
.min16float => .{ .bits = 16, .p = .{ .floating = true, .min_precision = true } },
|
||||
.min12int => .{ .bits = 12, .p = .{ .integer = true, .min_precision = true } },
|
||||
.min16int => .{ .bits = 16, .p = .{ .integer = true, .min_precision = true } },
|
||||
.min16uint => .{ .bits = 16, .p = .{ .integer = true, .unsigned = true, .min_precision = true } },
|
||||
};
|
||||
}
|
||||
|
||||
/// The component type of a binary operation on `a` and `b`: a port of
|
||||
/// dxc's CombineBasicTypes.
|
||||
pub fn combine(a: Scalar, b: Scalar) Scalar {
|
||||
if (a == b) return a;
|
||||
const l = a.props();
|
||||
const r = b.props();
|
||||
var bits = @max(l.bits, r.bits);
|
||||
const lb: u16 = @bitCast(l.p);
|
||||
const rb: u16 = @bitCast(r.p);
|
||||
const both: Props = @bitCast(lb & rb);
|
||||
const either: Props = @bitCast(lb | rb);
|
||||
if (both.boolean) return .bool;
|
||||
const float_result = either.floating;
|
||||
if (both.literal) return if (float_result) .literal_float else .literal_int;
|
||||
var res: Props = .{
|
||||
.integer = both.integer,
|
||||
.min_precision = both.min_precision,
|
||||
.partial_precision = both.partial_precision,
|
||||
.floating = either.floating,
|
||||
.unsigned = !float_result and either.unsigned,
|
||||
};
|
||||
// A literal or bool operand takes its precision from the other.
|
||||
if (either.literal or either.boolean) {
|
||||
res.min_precision = either.min_precision;
|
||||
res.partial_precision = res.partial_precision or either.partial_precision;
|
||||
}
|
||||
if (res.partial_precision) return .half;
|
||||
// Only one side is floating: the result comes from that side.
|
||||
if (float_result and !both.floating) {
|
||||
const f = if (l.p.floating) l else r;
|
||||
res = f.p;
|
||||
bits = f.bits;
|
||||
}
|
||||
if (bits == 0) bits = 32;
|
||||
if (float_result) return switch (bits) {
|
||||
10 => .min10float,
|
||||
16 => if (res.min_precision) .min16float else .float16,
|
||||
64 => .double,
|
||||
else => .float,
|
||||
};
|
||||
return switch (bits) {
|
||||
12 => .min12int,
|
||||
16 => if (res.unsigned)
|
||||
(if (res.min_precision) .min16uint else .uint16)
|
||||
else
|
||||
(if (res.min_precision) .min16int else .int16),
|
||||
64 => if (res.unsigned) .uint64 else .int64,
|
||||
else => if (res.unsigned) .uint else .int,
|
||||
};
|
||||
}
|
||||
|
||||
/// Rank for the usual arithmetic conversions: higher wins.
|
||||
pub fn rank(s: Scalar) u8 {
|
||||
return switch (s) {
|
||||
.bool => 0,
|
||||
.literal_int => 1,
|
||||
.min12int, .min16int => 2,
|
||||
.min16uint => 3,
|
||||
.int16 => 4,
|
||||
.uint16 => 5,
|
||||
.int, .int8_4packed => 6,
|
||||
.uint, .uint8_4packed => 7,
|
||||
.int64 => 8,
|
||||
.uint64 => 9,
|
||||
.literal_float => 10,
|
||||
.min10float, .min16float => 11,
|
||||
.float16 => 12,
|
||||
.half => 13,
|
||||
.float => 14,
|
||||
.double => 15,
|
||||
};
|
||||
}
|
||||
|
||||
/// Size in bytes of the component as stored (32-bit unless noted).
|
||||
pub fn size(s: Scalar) u32 {
|
||||
return switch (s) {
|
||||
.double, .int64, .uint64 => 8,
|
||||
.int16, .uint16, .float16 => 2,
|
||||
else => 4,
|
||||
};
|
||||
}
|
||||
|
||||
/// The concrete type a literal becomes when nothing else decides.
|
||||
pub fn concrete(s: Scalar) Scalar {
|
||||
return switch (s) {
|
||||
.literal_int => .int,
|
||||
.literal_float => .float,
|
||||
else => s,
|
||||
};
|
||||
}
|
||||
|
||||
/// HLSL spelling, as dxc prints it.
|
||||
pub fn name(s: Scalar) []const u8 {
|
||||
return switch (s) {
|
||||
.bool => "bool",
|
||||
.int => "int",
|
||||
.uint => "uint",
|
||||
.half => "half",
|
||||
.float => "float",
|
||||
.double => "double",
|
||||
.min16float => "min16float",
|
||||
.min10float => "min10float",
|
||||
.min16int => "min16int",
|
||||
.min12int => "min12int",
|
||||
.min16uint => "min16uint",
|
||||
.int16 => "int16_t",
|
||||
.uint16 => "uint16_t",
|
||||
.int64 => "int64_t",
|
||||
.uint64 => "uint64_t",
|
||||
.float16 => "float16_t",
|
||||
.literal_int => "literal int",
|
||||
.literal_float => "literal float",
|
||||
.int8_4packed => "int8_t4_packed",
|
||||
.uint8_4packed => "uint8_t4_packed",
|
||||
};
|
||||
}
|
||||
|
||||
/// Scalar named by an HLSL keyword (`dword`, `float32_t` are aliases).
|
||||
pub fn fromName(n: []const u8) ?Scalar {
|
||||
const map = [_]struct { []const u8, Scalar }{
|
||||
.{ "bool", .bool }, .{ "int", .int }, .{ "uint", .uint },
|
||||
.{ "dword", .uint }, .{ "half", .half }, .{ "float", .float },
|
||||
.{ "double", .double }, .{ "min16float", .min16float }, .{ "min10float", .min10float },
|
||||
.{ "min16int", .min16int }, .{ "min12int", .min12int }, .{ "min16uint", .min16uint },
|
||||
.{ "int16_t", .int16 }, .{ "uint16_t", .uint16 }, .{ "int32_t", .int },
|
||||
.{ "uint32_t", .uint }, .{ "int64_t", .int64 }, .{ "uint64_t", .uint64 },
|
||||
.{ "float16_t", .float16 }, .{ "float32_t", .float }, .{ "float64_t", .double },
|
||||
.{ "int8_t4_packed", .int8_4packed }, .{ "uint8_t4_packed", .uint8_4packed },
|
||||
};
|
||||
for (map) |m| if (std.mem.eql(u8, m[0], n)) return m[1];
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
pub const ResourceKind = enum(u8) {
|
||||
buffer,
|
||||
rw_buffer,
|
||||
byte_address_buffer,
|
||||
rw_byte_address_buffer,
|
||||
structured_buffer,
|
||||
rw_structured_buffer,
|
||||
append_structured_buffer,
|
||||
consume_structured_buffer,
|
||||
texture1d,
|
||||
texture1d_array,
|
||||
texture2d,
|
||||
texture2d_array,
|
||||
texture2dms,
|
||||
texture2dms_array,
|
||||
texture3d,
|
||||
texture_cube,
|
||||
texture_cube_array,
|
||||
rw_texture1d,
|
||||
rw_texture1d_array,
|
||||
rw_texture2d,
|
||||
rw_texture2d_array,
|
||||
rw_texture2dms,
|
||||
rw_texture2dms_array,
|
||||
rw_texture3d,
|
||||
constant_buffer,
|
||||
texture_buffer,
|
||||
raytracing_acceleration_structure,
|
||||
feedback_texture2d,
|
||||
feedback_texture2d_array,
|
||||
/// Any other builtin object (RayQuery, node records, vk:: types...):
|
||||
/// accepted, with methods resolved through the intrinsic table.
|
||||
other,
|
||||
|
||||
pub fn isWritable(k: ResourceKind) bool {
|
||||
return switch (k) {
|
||||
.rw_buffer, .rw_byte_address_buffer, .rw_structured_buffer, .append_structured_buffer, .rw_texture1d, .rw_texture1d_array, .rw_texture2d, .rw_texture2d_array, .rw_texture2dms, .rw_texture2dms_array, .rw_texture3d => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
/// Dimensions of the integer index used by operator[] (0: no indexing).
|
||||
pub fn indexDims(k: ResourceKind) u8 {
|
||||
return switch (k) {
|
||||
.buffer, .rw_buffer, .structured_buffer, .rw_structured_buffer, .texture1d, .rw_texture1d => 1,
|
||||
.texture1d_array, .rw_texture1d_array, .texture2d, .rw_texture2d, .texture2dms, .rw_texture2dms => 2,
|
||||
.texture2d_array, .rw_texture2d_array, .texture2dms_array, .rw_texture2dms_array, .texture3d, .rw_texture3d => 3,
|
||||
else => 0,
|
||||
};
|
||||
}
|
||||
|
||||
pub const names = [_]struct { []const u8, ResourceKind }{
|
||||
.{ "Buffer", .buffer }, .{ "RWBuffer", .rw_buffer },
|
||||
.{ "ByteAddressBuffer", .byte_address_buffer }, .{ "RWByteAddressBuffer", .rw_byte_address_buffer },
|
||||
.{ "StructuredBuffer", .structured_buffer }, .{ "RWStructuredBuffer", .rw_structured_buffer },
|
||||
.{ "AppendStructuredBuffer", .append_structured_buffer }, .{ "ConsumeStructuredBuffer", .consume_structured_buffer },
|
||||
.{ "Texture1D", .texture1d }, .{ "Texture1DArray", .texture1d_array },
|
||||
.{ "Texture2D", .texture2d }, .{ "Texture2DArray", .texture2d_array },
|
||||
.{ "Texture2DMS", .texture2dms }, .{ "Texture2DMSArray", .texture2dms_array },
|
||||
.{ "Texture3D", .texture3d }, .{ "TextureCube", .texture_cube },
|
||||
.{ "TextureCubeArray", .texture_cube_array }, .{ "RWTexture1D", .rw_texture1d },
|
||||
.{ "RWTexture1DArray", .rw_texture1d_array }, .{ "RWTexture2D", .rw_texture2d },
|
||||
.{ "RWTexture2DArray", .rw_texture2d_array }, .{ "RWTexture2DMS", .rw_texture2dms },
|
||||
.{ "RWTexture2DMSArray", .rw_texture2dms_array }, .{ "RWTexture3D", .rw_texture3d },
|
||||
.{ "ConstantBuffer", .constant_buffer }, .{ "TextureBuffer", .texture_buffer },
|
||||
.{ "RaytracingAccelerationStructure", .raytracing_acceleration_structure }, .{ "FeedbackTexture2D", .feedback_texture2d },
|
||||
.{ "FeedbackTexture2DArray", .feedback_texture2d_array },
|
||||
// Rasterizer-ordered views behave like their RW counterparts.
|
||||
.{ "RasterizerOrderedBuffer", .rw_buffer },
|
||||
.{ "RasterizerOrderedByteAddressBuffer", .rw_byte_address_buffer }, .{ "RasterizerOrderedStructuredBuffer", .rw_structured_buffer },
|
||||
.{ "RasterizerOrderedTexture1D", .rw_texture1d }, .{ "RasterizerOrderedTexture1DArray", .rw_texture1d_array },
|
||||
.{ "RasterizerOrderedTexture2D", .rw_texture2d }, .{ "RasterizerOrderedTexture2DArray", .rw_texture2d_array },
|
||||
.{ "RasterizerOrderedTexture3D", .rw_texture3d },
|
||||
};
|
||||
|
||||
pub fn fromName(n: []const u8) ?ResourceKind {
|
||||
for (names) |m| if (std.mem.eql(u8, m[0], n)) return m[1];
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
pub const Field = struct {
|
||||
name: []const u8,
|
||||
type: TypeId,
|
||||
};
|
||||
|
||||
/// A struct's layout-relevant information. Methods live in Sema.
|
||||
pub const StructInfo = struct {
|
||||
name: []const u8,
|
||||
fields: std.ArrayList(Field) = .empty,
|
||||
/// Direct base structs (HLSL 2021 single inheritance, in practice).
|
||||
bases: std.ArrayList(*StructInfo) = .empty,
|
||||
/// Opaque pointer to Sema's per-struct data (methods, base).
|
||||
sema: ?*anyopaque = null,
|
||||
complete: bool = false,
|
||||
};
|
||||
|
||||
pub const EnumInfo = struct {
|
||||
name: []const u8,
|
||||
underlying: Scalar,
|
||||
scoped: bool,
|
||||
};
|
||||
|
||||
pub const Type = union(enum) {
|
||||
void,
|
||||
/// The type of an ill-formed expression: suppresses follow-on errors.
|
||||
@"error",
|
||||
scalar: Scalar,
|
||||
vector: struct { elem: Scalar, len: u8 },
|
||||
matrix: struct { elem: Scalar, rows: u8, cols: u8 },
|
||||
/// `len == 0` means unsized (`float a[]`).
|
||||
array: struct { elem: TypeId, len: u32 },
|
||||
@"struct": *StructInfo,
|
||||
@"enum": *EnumInfo,
|
||||
/// `elem` is the template argument (or the void type when absent).
|
||||
resource: struct { kind: ResourceKind, elem: TypeId, name: []const u8 },
|
||||
sampler: struct { comparison: bool },
|
||||
string,
|
||||
/// PointStream / LineStream / TriangleStream<T>.
|
||||
stream: struct { kind: enum { point, line, triangle }, elem: TypeId },
|
||||
/// InputPatch / OutputPatch<T, N>.
|
||||
patch: struct { output: bool, elem: TypeId, count: u32 },
|
||||
/// ResourceDescriptorHeap / SamplerDescriptorHeap (SM 6.6).
|
||||
descriptor_heap: struct { sampler: bool },
|
||||
/// `ResourceDescriptorHeap[i]`: converts to any resource / sampler.
|
||||
dynamic_resource,
|
||||
};
|
||||
|
||||
/// Interns types. Ids 0 and 1 are `error` and `void`.
|
||||
pub const TypeTable = struct {
|
||||
gpa: Allocator,
|
||||
types: std.ArrayList(Type) = .empty,
|
||||
map: std.AutoHashMapUnmanaged(Key, TypeId) = .empty,
|
||||
|
||||
pub const error_type: TypeId = 0;
|
||||
pub const void_type: TypeId = 1;
|
||||
|
||||
/// Hashable identity of structural types.
|
||||
const Key = struct { tag: u8, a: u64, b: u64 };
|
||||
|
||||
pub fn init(gpa: Allocator) !TypeTable {
|
||||
var t: TypeTable = .{ .gpa = gpa };
|
||||
try t.types.append(gpa, .@"error");
|
||||
try t.types.append(gpa, .void);
|
||||
return t;
|
||||
}
|
||||
|
||||
pub fn deinit(t: *TypeTable) void {
|
||||
t.types.deinit(t.gpa);
|
||||
t.map.deinit(t.gpa);
|
||||
}
|
||||
|
||||
pub fn get(t: *const TypeTable, id: TypeId) Type {
|
||||
return t.types.items[id];
|
||||
}
|
||||
|
||||
fn keyOf(ty: Type) ?Key {
|
||||
return switch (ty) {
|
||||
.void, .@"error" => null,
|
||||
.scalar => |s| .{ .tag = 1, .a = @backingInt(s), .b = 0 },
|
||||
.vector => |v| .{ .tag = 2, .a = @backingInt(v.elem), .b = v.len },
|
||||
.matrix => |m| .{ .tag = 3, .a = @backingInt(m.elem), .b = (@as(u64, m.rows) << 8) | m.cols },
|
||||
.array => |a| .{ .tag = 4, .a = a.elem, .b = a.len },
|
||||
.@"struct" => |s| .{ .tag = 5, .a = @intFromPtr(s), .b = 0 },
|
||||
.@"enum" => |e| .{ .tag = 6, .a = @intFromPtr(e), .b = 0 },
|
||||
.resource => |r| .{ .tag = 7, .a = (@as(u64, @backingInt(r.kind)) << 32) | r.elem, .b = std.hash.Wyhash.hash(0, r.name) },
|
||||
.sampler => |s| .{ .tag = 8, .a = @intFromBool(s.comparison), .b = 0 },
|
||||
.string => .{ .tag = 9, .a = 0, .b = 0 },
|
||||
.stream => |s| .{ .tag = 10, .a = @backingInt(s.kind), .b = s.elem },
|
||||
.patch => |p| .{ .tag = 11, .a = (@as(u64, @intFromBool(p.output)) << 32) | p.elem, .b = p.count },
|
||||
.descriptor_heap => |h| .{ .tag = 12, .a = @intFromBool(h.sampler), .b = 0 },
|
||||
.dynamic_resource => .{ .tag = 13, .a = 0, .b = 0 },
|
||||
};
|
||||
}
|
||||
|
||||
pub fn intern(t: *TypeTable, ty: Type) !TypeId {
|
||||
const key = keyOf(ty) orelse return if (ty == .void) void_type else error_type;
|
||||
const gop = try t.map.getOrPut(t.gpa, key);
|
||||
if (gop.found_existing) return gop.value_ptr.*;
|
||||
try t.types.append(t.gpa, ty);
|
||||
gop.value_ptr.* = @intCast(t.types.items.len - 1);
|
||||
return gop.value_ptr.*;
|
||||
}
|
||||
|
||||
pub fn scalar(t: *TypeTable, s: Scalar) !TypeId {
|
||||
return t.intern(.{ .scalar = s });
|
||||
}
|
||||
|
||||
/// `len == 1` vectors are kept distinct from scalars (float1 != float).
|
||||
pub fn vector(t: *TypeTable, s: Scalar, len: u8) !TypeId {
|
||||
return t.intern(.{ .vector = .{ .elem = s, .len = len } });
|
||||
}
|
||||
|
||||
pub fn matrix(t: *TypeTable, s: Scalar, rows: u8, cols: u8) !TypeId {
|
||||
return t.intern(.{ .matrix = .{ .elem = s, .rows = rows, .cols = cols } });
|
||||
}
|
||||
|
||||
pub fn array(t: *TypeTable, elem: TypeId, len: u32) !TypeId {
|
||||
return t.intern(.{ .array = .{ .elem = elem, .len = len } });
|
||||
}
|
||||
|
||||
/// Component type of a numeric (scalar / vector / matrix) type.
|
||||
pub fn component(t: *const TypeTable, id: TypeId) ?Scalar {
|
||||
return switch (t.get(id)) {
|
||||
.scalar => |s| s,
|
||||
.vector => |v| v.elem,
|
||||
.matrix => |m| m.elem,
|
||||
.@"enum" => |e| e.underlying,
|
||||
else => null,
|
||||
};
|
||||
}
|
||||
|
||||
pub const Shape = struct { rows: u8, cols: u8, kind: enum { scalar, vector, matrix } };
|
||||
|
||||
/// Shape of a numeric type: scalars are 1x1, vectors 1xN.
|
||||
pub fn shape(t: *const TypeTable, id: TypeId) ?Shape {
|
||||
return switch (t.get(id)) {
|
||||
.scalar, .@"enum" => .{ .rows = 1, .cols = 1, .kind = .scalar },
|
||||
.vector => |v| .{ .rows = 1, .cols = v.len, .kind = .vector },
|
||||
.matrix => |m| .{ .rows = m.rows, .cols = m.cols, .kind = .matrix },
|
||||
else => null,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn isNumeric(t: *const TypeTable, id: TypeId) bool {
|
||||
return t.component(id) != null;
|
||||
}
|
||||
|
||||
/// Build a numeric type of `shape` with component `s`.
|
||||
pub fn withShape(t: *TypeTable, s: Scalar, sh: Shape) !TypeId {
|
||||
return switch (sh.kind) {
|
||||
.scalar => t.scalar(s),
|
||||
.vector => t.vector(s, sh.cols),
|
||||
.matrix => t.matrix(s, sh.rows, sh.cols),
|
||||
};
|
||||
}
|
||||
|
||||
/// Same shape as `id`, different component.
|
||||
pub fn withComponent(t: *TypeTable, id: TypeId, s: Scalar) !TypeId {
|
||||
return t.withShape(s, t.shape(id) orelse return error_type);
|
||||
}
|
||||
|
||||
/// Number of scalar components (flattened), or null for non-numeric
|
||||
/// aggregates whose size is not defined.
|
||||
pub fn componentCount(t: *const TypeTable, id: TypeId) ?u32 {
|
||||
return switch (t.get(id)) {
|
||||
.scalar, .@"enum" => 1,
|
||||
.vector => |v| v.len,
|
||||
.matrix => |m| @as(u32, m.rows) * m.cols,
|
||||
.array => |a| if (a.len == 0) null else if (t.componentCount(a.elem)) |n| n * a.len else null,
|
||||
.@"struct" => |s| blk: {
|
||||
var n: u32 = 0;
|
||||
for (s.fields.items) |f| n += t.componentCount(f.type) orelse break :blk null;
|
||||
break :blk n;
|
||||
},
|
||||
else => null,
|
||||
};
|
||||
}
|
||||
|
||||
/// Spelling for diagnostics, close to dxc's (`vector<float, 3>`,
|
||||
/// `float4`, `MyStruct`, `Texture2D<float4>`).
|
||||
pub fn format(t: *const TypeTable, gpa: Allocator, id: TypeId) Allocator.Error![]const u8 {
|
||||
return switch (t.get(id)) {
|
||||
.void => "void",
|
||||
.@"error" => "<error>",
|
||||
.scalar => |s| s.name(),
|
||||
.vector => |v| std.fmt.allocPrint(gpa, "vector<{s}, {d}>", .{ v.elem.name(), v.len }),
|
||||
.matrix => |m| std.fmt.allocPrint(gpa, "matrix<{s}, {d}, {d}>", .{ m.elem.name(), m.rows, m.cols }),
|
||||
.array => |a| if (a.len == 0)
|
||||
std.fmt.allocPrint(gpa, "{s}[]", .{try t.format(gpa, a.elem)})
|
||||
else
|
||||
std.fmt.allocPrint(gpa, "{s}[{d}]", .{ try t.format(gpa, a.elem), a.len }),
|
||||
.@"struct" => |s| s.name,
|
||||
.@"enum" => |e| e.name,
|
||||
.resource => |r| if (r.elem == void_type) r.name else std.fmt.allocPrint(gpa, "{s}<{s}>", .{ r.name, try t.format(gpa, r.elem) }),
|
||||
.sampler => |s| if (s.comparison) "SamplerComparisonState" else "SamplerState",
|
||||
.string => "string",
|
||||
.stream => |s| std.fmt.allocPrint(gpa, "{s}Stream<{s}>", .{ switch (s.kind) {
|
||||
.point => "Point",
|
||||
.line => "Line",
|
||||
.triangle => "Triangle",
|
||||
}, try t.format(gpa, s.elem) }),
|
||||
.patch => |p| std.fmt.allocPrint(gpa, "{s}Patch<{s}, {d}>", .{ if (p.output) "Output" else "Input", try t.format(gpa, p.elem), p.count }),
|
||||
.descriptor_heap => |h| if (h.sampler) "SamplerDescriptorHeap" else "ResourceDescriptorHeap",
|
||||
.dynamic_resource => "<dynamic resource>",
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
test "interning and shapes" {
|
||||
var t = try TypeTable.init(std.testing.allocator);
|
||||
defer t.deinit();
|
||||
const f4 = try t.vector(.float, 4);
|
||||
try std.testing.expectEqual(f4, try t.vector(.float, 4));
|
||||
try std.testing.expect(f4 != try t.vector(.float, 3));
|
||||
try std.testing.expect(try t.vector(.float, 1) != try t.scalar(.float));
|
||||
const m = try t.matrix(.float, 4, 4);
|
||||
try std.testing.expectEqual(@as(?u32, 16), t.componentCount(m));
|
||||
try std.testing.expectEqual(try t.vector(.int, 4), try t.withComponent(f4, .int));
|
||||
const s = try t.format(std.testing.allocator, f4);
|
||||
defer std.testing.allocator.free(s);
|
||||
try std.testing.expectEqualStrings("vector<float, 4>", s);
|
||||
}
|
||||
|
|
@ -0,0 +1,233 @@
|
|||
//! Build-time generator: reads dxc's intrinsic declarations
|
||||
//! (vendor/dxc/gen_intrin_main.txt) and writes a Zig table that Sema uses
|
||||
//! for intrinsic and builtin-method overload resolution.
|
||||
//!
|
||||
//! Usage: gen_intrinsics <gen_intrin_main.txt> <out.zig>
|
||||
//!
|
||||
//! Declaration syntax (see the header of gen_intrin_main.txt):
|
||||
//! <type> [[attrs]] <name>(<qual> <type> <name>, ...) [: <op>];
|
||||
//! grouped into `namespace X { ... } namespace` blocks.
|
||||
|
||||
const std = @import("std");
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
const Spec = struct {
|
||||
qual: []const u8 = "in",
|
||||
match_layout: i32 = std.math.minInt(i32),
|
||||
match_comp: i32 = std.math.minInt(i32),
|
||||
special: []const u8 = "none",
|
||||
type_n: u32 = 0,
|
||||
base: []const u8 = "",
|
||||
any_layout: bool = false,
|
||||
dims: std.ArrayList([]const u8) = .empty,
|
||||
name: []const u8 = "",
|
||||
};
|
||||
|
||||
const Decl = struct {
|
||||
ns: []const u8,
|
||||
name: []const u8,
|
||||
ret: Spec,
|
||||
params: std.ArrayList(Spec) = .empty,
|
||||
varargs: bool = false,
|
||||
attrs: []const u8,
|
||||
op: []const u8,
|
||||
};
|
||||
|
||||
pub fn main(init: std.process.Init) !void {
|
||||
const a = init.arena.allocator();
|
||||
const io = init.io;
|
||||
const args = try init.minimal.args.toSlice(a);
|
||||
if (args.len != 3) return error.Usage;
|
||||
const text = try std.Io.Dir.cwd().readFileAlloc(io, args[1], a, .limited(1 << 20));
|
||||
|
||||
var decls: std.ArrayList(Decl) = .empty;
|
||||
var ns: []const u8 = "";
|
||||
var lines = std.mem.splitScalar(u8, text, '\n');
|
||||
var lineno: usize = 0;
|
||||
while (lines.next()) |raw| {
|
||||
lineno += 1;
|
||||
const line = std.mem.trim(u8, raw, " \t\r");
|
||||
if (line.len == 0 or std.mem.startsWith(u8, line, "//") or line[0] == '#') continue;
|
||||
if (std.mem.startsWith(u8, line, "namespace ")) {
|
||||
ns = std.mem.trim(u8, line["namespace ".len..], " {");
|
||||
continue;
|
||||
}
|
||||
if (line[0] == '}') continue;
|
||||
const d = parseDecl(a, ns, line) catch |e| {
|
||||
std.debug.print("gen_intrinsics: line {d}: {s}: {s}\n", .{ lineno, @errorName(e), line });
|
||||
return e;
|
||||
};
|
||||
try decls.append(a, d);
|
||||
}
|
||||
|
||||
var out: std.Io.Writer.Allocating = .init(a);
|
||||
try emit(&out.writer, decls.items);
|
||||
try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = args[2], .data = out.written() });
|
||||
}
|
||||
|
||||
fn parseDecl(a: Allocator, ns: []const u8, line_in: []const u8) !Decl {
|
||||
var line = std.mem.trimEnd(u8, line_in, ";");
|
||||
// Optional `: op` after the closing parenthesis.
|
||||
var op: []const u8 = "";
|
||||
const close = std.mem.lastIndexOfScalar(u8, line, ')') orelse return error.NoParen;
|
||||
if (std.mem.indexOfScalarPos(u8, line, close, ':')) |colon| {
|
||||
op = std.mem.trim(u8, line[colon + 1 ..], " ");
|
||||
line = line[0..colon];
|
||||
}
|
||||
const open_attr = std.mem.indexOf(u8, line, "[[") orelse return error.NoAttrs;
|
||||
const close_attr = std.mem.indexOfPos(u8, line, open_attr, "]]") orelse return error.NoAttrs;
|
||||
const ret_text = std.mem.trim(u8, line[0..open_attr], " ");
|
||||
const attrs = line[open_attr + 2 .. close_attr];
|
||||
const rest = std.mem.trim(u8, line[close_attr + 2 ..], " ");
|
||||
const lp = std.mem.indexOfScalar(u8, rest, '(') orelse return error.NoParen;
|
||||
const rp = std.mem.lastIndexOfScalar(u8, rest, ')') orelse return error.NoParen;
|
||||
var d: Decl = .{
|
||||
.ns = ns,
|
||||
.name = std.mem.trim(u8, rest[0..lp], " "),
|
||||
.ret = try parseSpec(a, ret_text, false),
|
||||
.attrs = attrs,
|
||||
.op = op,
|
||||
};
|
||||
const params_text = std.mem.trim(u8, rest[lp + 1 .. rp], " ");
|
||||
if (params_text.len > 0) {
|
||||
var depth: u32 = 0;
|
||||
var start: usize = 0;
|
||||
for (params_text, 0..) |c, i| {
|
||||
if (c == '<') depth += 1;
|
||||
if (c == '>') depth -= 1;
|
||||
if ((c == ',' and depth == 0) or i == params_text.len - 1) {
|
||||
const end = if (c == ',' and depth == 0) i else i + 1;
|
||||
const p = std.mem.trim(u8, params_text[start..end], " ");
|
||||
start = i + 1;
|
||||
if (std.mem.eql(u8, p, "...")) {
|
||||
d.varargs = true;
|
||||
continue;
|
||||
}
|
||||
try d.params.append(a, try parseSpec(a, p, true));
|
||||
}
|
||||
}
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
/// `[qual...] type [name]`, where type is `$classT`, `$funcT`, `$typeN`,
|
||||
/// or `[$match<X, Y>] base[<dims>]`.
|
||||
fn parseSpec(a: Allocator, text: []const u8, is_param: bool) !Spec {
|
||||
var s: Spec = .{};
|
||||
var t = text;
|
||||
// Qualifiers.
|
||||
while (true) {
|
||||
t = std.mem.trimStart(u8, t, " ");
|
||||
const quals = [_][]const u8{ "inout ", "in ", "out ", "ref ", "row_major ", "col_major " };
|
||||
var matched = false;
|
||||
for (quals) |q| {
|
||||
if (std.mem.startsWith(u8, t, q)) {
|
||||
const word = q[0 .. q.len - 1];
|
||||
if (!std.mem.eql(u8, word, "row_major") and !std.mem.eql(u8, word, "col_major")) s.qual = word;
|
||||
t = t[q.len..];
|
||||
matched = true;
|
||||
}
|
||||
}
|
||||
if (!matched) break;
|
||||
}
|
||||
if (std.mem.startsWith(u8, t, "$match<")) {
|
||||
const end = std.mem.indexOfScalar(u8, t, '>') orelse return error.BadMatch;
|
||||
var it = std.mem.splitScalar(u8, t["$match<".len..end], ',');
|
||||
s.match_layout = try std.fmt.parseInt(i32, std.mem.trim(u8, it.next().?, " "), 10);
|
||||
s.match_comp = try std.fmt.parseInt(i32, std.mem.trim(u8, it.next() orelse return error.BadMatch, " "), 10);
|
||||
t = std.mem.trimStart(u8, t[end + 1 ..], " ");
|
||||
}
|
||||
if (std.mem.startsWith(u8, t, "$classT")) {
|
||||
s.special = "class_t";
|
||||
t = t["$classT".len..];
|
||||
} else if (std.mem.startsWith(u8, t, "$funcT")) {
|
||||
s.special = "func_t";
|
||||
t = t["$funcT".len..];
|
||||
} else if (std.mem.startsWith(u8, t, "$type")) {
|
||||
var i: usize = "$type".len;
|
||||
while (i < t.len and std.ascii.isDigit(t[i])) i += 1;
|
||||
s.special = "type_n";
|
||||
s.type_n = try std.fmt.parseInt(u32, t["$type".len..i], 10);
|
||||
t = t[i..];
|
||||
} else {
|
||||
var i: usize = 0;
|
||||
while (i < t.len and (std.ascii.isAlphanumeric(t[i]) or t[i] == '_')) i += 1;
|
||||
s.base = t[0..i];
|
||||
t = t[i..];
|
||||
if (t.len > 0 and t[0] == '<') {
|
||||
const end = std.mem.indexOfScalar(u8, t, '>') orelse return error.BadLayout;
|
||||
const inner = std.mem.trim(u8, t[1..end], " ");
|
||||
if (inner.len == 0) {
|
||||
s.any_layout = true;
|
||||
} else {
|
||||
var it = std.mem.splitScalar(u8, inner, ',');
|
||||
while (it.next()) |dim| try s.dims.append(a, std.mem.trim(u8, dim, " "));
|
||||
}
|
||||
t = t[end + 1 ..];
|
||||
}
|
||||
}
|
||||
if (is_param) s.name = std.mem.trim(u8, t, " ");
|
||||
return s;
|
||||
}
|
||||
|
||||
fn emitSpec(w: *std.Io.Writer, s: Spec) !void {
|
||||
try w.print(".{{ .qual = .{s}, .special = .{s}, .type_n = {d}, .base = \"{s}\", .any_layout = {}, .dims = &.{{", .{ if (std.mem.eql(u8, s.qual, "inout")) "inout" else if (std.mem.eql(u8, s.qual, "out")) "out" else if (std.mem.eql(u8, s.qual, "ref")) "ref" else "in", s.special, s.type_n, s.base, s.any_layout });
|
||||
for (s.dims.items, 0..) |d, i| {
|
||||
if (i > 0) try w.writeAll(", ");
|
||||
try w.print("\"{s}\"", .{d});
|
||||
}
|
||||
try w.writeAll("}, .match_layout = ");
|
||||
if (s.match_layout == std.math.minInt(i32)) try w.writeAll("null") else try w.print("{d}", .{s.match_layout});
|
||||
try w.writeAll(", .match_comp = ");
|
||||
if (s.match_comp == std.math.minInt(i32)) try w.writeAll("null") else try w.print("{d}", .{s.match_comp});
|
||||
try w.print(", .name = \"{s}\" }}", .{s.name});
|
||||
}
|
||||
|
||||
fn emit(w: *std.Io.Writer, decls: []const Decl) !void {
|
||||
try w.writeAll(
|
||||
\\//! Generated by tools/gen_intrinsics.zig from vendor/dxc/gen_intrin_main.txt.
|
||||
\\//! Do not edit.
|
||||
\\
|
||||
\\pub const Qual = enum { in, out, inout, ref };
|
||||
\\pub const Special = enum { none, class_t, func_t, type_n };
|
||||
\\
|
||||
\\pub const Spec = struct {
|
||||
\\ qual: Qual,
|
||||
\\ special: Special,
|
||||
\\ type_n: u32,
|
||||
\\ /// Component class: `float_like`, `numeric`, `uint`, `sampler`, ...
|
||||
\\ base: []const u8,
|
||||
\\ /// `<>`: any scalar / vector / matrix layout.
|
||||
\\ any_layout: bool,
|
||||
\\ /// Layout dimensions: none (scalar), `{"4"}`, `{"c"}`, `{"r", "c"}` ...
|
||||
\\ dims: []const []const u8,
|
||||
\\ match_layout: ?i32,
|
||||
\\ match_comp: ?i32,
|
||||
\\ name: []const u8,
|
||||
\\};
|
||||
\\
|
||||
\\pub const Intrinsic = struct {
|
||||
\\ namespace: []const u8,
|
||||
\\ name: []const u8,
|
||||
\\ ret: Spec,
|
||||
\\ params: []const Spec,
|
||||
\\ varargs: bool,
|
||||
\\ attrs: []const u8,
|
||||
\\ op: []const u8,
|
||||
\\};
|
||||
\\
|
||||
\\pub const intrinsics = [_]Intrinsic{
|
||||
\\
|
||||
);
|
||||
for (decls) |d| {
|
||||
try w.print(" .{{ .namespace = \"{s}\", .name = \"{s}\", .ret = ", .{ d.ns, d.name });
|
||||
try emitSpec(w, d.ret);
|
||||
try w.writeAll(", .params = &.{");
|
||||
for (d.params.items, 0..) |p, i| {
|
||||
if (i > 0) try w.writeAll(", ");
|
||||
try emitSpec(w, p);
|
||||
}
|
||||
try w.print("}}, .varargs = {}, .attrs = \"{s}\", .op = \"{s}\" }},\n", .{ d.varargs, d.attrs, d.op });
|
||||
}
|
||||
try w.writeAll("};\n");
|
||||
}
|
||||
|
|
@ -5,6 +5,7 @@ Each entry records the source path and the DXC commit it was copied from.
|
|||
|
||||
| File | Source in DXC | DXC commit | License |
|
||||
|---|---|---|---|
|
||||
| `dxc/gen_intrin_main.txt` | `utils/hct/gen_intrin_main.txt` | 55a61aa79 | University of Illinois/NCSA (DXC) |
|
||||
| `dxc/HLSLOptions.td` | `include/dxc/Support/HLSLOptions.td` | d02056da2 | University of Illinois/NCSA (DXC) |
|
||||
| `hlsl-headers/` (all files) | `tools/clang/lib/Headers/hlsl/` | ecb18fb18 | Apache-2.0 WITH LLVM-exception (`hlsl-headers/LICENSE.txt`) |
|
||||
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue