Compare commits
No commits in common. "412600a56e8ee71bbcbca8ad953f1799693c665a" and "6e5860b1dbffc53e0424b49a429720f57ccf6b7f" have entirely different histories.
412600a56e
...
6e5860b1db
|
|
@ -1,7 +1,7 @@
|
||||||
//! Preprocessor benchmark: lexes / preprocesses a set of files in-process
|
//! Preprocessor benchmark: lexes / preprocesses a set of files in-process
|
||||||
//! and reports the best-of-N wall time and throughput.
|
//! and reports the best-of-N wall time and throughput.
|
||||||
//!
|
//!
|
||||||
//! Usage: pp_bench [-mode lex|load|pp|print|parse] [-iters N] <file-list.txt>
|
//! Usage: pp_bench [-mode lex|pp|print] [-iters N] <file-list.txt>
|
||||||
//! The file list has one path per line. File contents are read once and
|
//! The file list has one path per line. File contents are read once and
|
||||||
//! served from memory, so disk I/O is excluded from the timings.
|
//! served from memory, so disk I/O is excluded from the timings.
|
||||||
|
|
||||||
|
|
@ -10,7 +10,7 @@ const Io = std.Io;
|
||||||
const zdxc = @import("zdxc");
|
const zdxc = @import("zdxc");
|
||||||
const front = zdxc.front;
|
const front = zdxc.front;
|
||||||
|
|
||||||
const Mode = enum { lex, load, pp, print, parse };
|
const Mode = enum { lex, pp, print };
|
||||||
|
|
||||||
/// Serves each path from memory after the first read.
|
/// Serves each path from memory after the first read.
|
||||||
const CachedFs = struct {
|
const CachedFs = struct {
|
||||||
|
|
@ -98,18 +98,9 @@ fn runOne(gpa: std.mem.Allocator, cfs: *CachedFs, path: []const u8, mode: Mode)
|
||||||
}
|
}
|
||||||
|
|
||||||
var sm = front.source.SourceManager.init(arena, cfs.fileSystem());
|
var sm = front.source.SourceManager.init(arena, cfs.fileSystem());
|
||||||
if (mode == .load) {
|
|
||||||
const id = try sm.load(path) orelse return 0;
|
|
||||||
return sm.file(id).line_starts.len;
|
|
||||||
}
|
|
||||||
var diags = zdxc.Diagnostics.init(arena);
|
var diags = zdxc.Diagnostics.init(arena);
|
||||||
var pp = front.preproc.Preprocessor.init(arena, &sm, &diags, .{});
|
var pp = front.preproc.Preprocessor.init(arena, &sm, &diags, .{});
|
||||||
if (!try pp.enterMainFile(path)) return 0;
|
if (!try pp.enterMainFile(path)) return 0;
|
||||||
if (mode == .parse) {
|
|
||||||
var parser = try front.parser.Parser.fromPreprocessor(arena, &diags, &pp);
|
|
||||||
const tu = try parser.parseTranslationUnit();
|
|
||||||
return tu.decls.len + diags.error_count;
|
|
||||||
}
|
|
||||||
if (mode == .print) {
|
if (mode == .print) {
|
||||||
var out: Io.Writer.Allocating = .init(arena);
|
var out: Io.Writer.Allocating = .init(arena);
|
||||||
try front.pp_print.print(&pp, &out.writer);
|
try front.pp_print.print(&pp, &out.writer);
|
||||||
|
|
|
||||||
28
build.zig
28
build.zig
|
|
@ -9,26 +9,12 @@ pub fn build(b: *std.Build) void {
|
||||||
.target = target,
|
.target = target,
|
||||||
.optimize = optimize,
|
.optimize = optimize,
|
||||||
});
|
});
|
||||||
// dxc's option table, generated from the vendored tablegen file by a
|
|
||||||
// host tool (no tablegen or Python needed).
|
|
||||||
const gen_options = b.addExecutable(.{
|
|
||||||
.name = "gen_options",
|
|
||||||
.root_module = b.createModule(.{
|
|
||||||
.root_source_file = b.path("tools/gen_options.zig"),
|
|
||||||
.target = b.graph.host,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
const gen_options_run = b.addRunArtifact(gen_options);
|
|
||||||
gen_options_run.addFileArg(b.path("vendor/dxc/HLSLOptions.td"));
|
|
||||||
const options_table = gen_options_run.addOutputFileArg("options_table.zig");
|
|
||||||
|
|
||||||
const mod = b.addModule("zdxc", .{
|
const mod = b.addModule("zdxc", .{
|
||||||
.root_source_file = b.path("src/root.zig"),
|
.root_source_file = b.path("src/root.zig"),
|
||||||
.target = target,
|
.target = target,
|
||||||
.optimize = optimize,
|
.optimize = optimize,
|
||||||
.imports = &.{.{ .name = "hlsl_headers", .module = hlsl_headers }},
|
.imports = &.{.{ .name = "hlsl_headers", .module = hlsl_headers }},
|
||||||
});
|
});
|
||||||
mod.addAnonymousImport("options_table", .{ .root_source_file = options_table });
|
|
||||||
|
|
||||||
const exe = b.addExecutable(.{
|
const exe = b.addExecutable(.{
|
||||||
.name = "zdxc",
|
.name = "zdxc",
|
||||||
|
|
@ -61,20 +47,6 @@ pub fn build(b: *std.Build) void {
|
||||||
oracle.has_side_effects = true;
|
oracle.has_side_effects = true;
|
||||||
oracle_step.dependOn(&oracle.step);
|
oracle_step.dependOn(&oracle.step);
|
||||||
|
|
||||||
const oracle_parse_step = b.step("oracle-parse", "Parse every dxc-valid corpus file with zdxc");
|
|
||||||
const oracle_parse = b.addSystemCommand(&.{ "sh", "test/oracle/parse.sh" });
|
|
||||||
oracle_parse.addArtifactArg(exe);
|
|
||||||
oracle_parse.setCwd(b.path("."));
|
|
||||||
oracle_parse.has_side_effects = true;
|
|
||||||
oracle_parse_step.dependOn(&oracle_parse.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);
|
|
||||||
oracle_cli.setCwd(b.path("."));
|
|
||||||
oracle_cli.has_side_effects = true;
|
|
||||||
oracle_cli_step.dependOn(&oracle_cli.step);
|
|
||||||
|
|
||||||
// Benchmarks always build optimized so numbers are comparable.
|
// Benchmarks always build optimized so numbers are comparable.
|
||||||
const bench = b.addExecutable(.{
|
const bench = b.addExecutable(.{
|
||||||
.name = "pp_bench",
|
.name = "pp_bench",
|
||||||
|
|
|
||||||
|
|
@ -1,310 +0,0 @@
|
||||||
# libzdxc: matching DXC's library API
|
|
||||||
|
|
||||||
Status: investigation notes, not yet implemented. Source references are to the
|
|
||||||
DXC tree at `f9fc72ad3`.
|
|
||||||
|
|
||||||
## How DXC works as a library
|
|
||||||
|
|
||||||
`dxcompiler` (`libdxcompiler.so` / `.dylib`, `dxcompiler.dll`) exports
|
|
||||||
exactly two C symbols (`tools/clang/tools/dxcompiler/dxcompiler.def`):
|
|
||||||
|
|
||||||
```c
|
|
||||||
HRESULT DxcCreateInstance (REFCLSID rclsid, REFIID riid, void **ppv);
|
|
||||||
HRESULT DxcCreateInstance2(IMalloc *pMalloc, REFCLSID rclsid, REFIID riid, void **ppv);
|
|
||||||
```
|
|
||||||
|
|
||||||
Everything else is a COM-style interface reached from those two calls.
|
|
||||||
`DxcCreateInstance` is a CLSID switch (`dxcapi.cpp`,
|
|
||||||
`ThreadMallocDxcCreateInstance`) that returns `REGDB_E_CLASSNOTREG`
|
|
||||||
(0x80040154) for unknown classes. `DxcCreateInstance2` installs a
|
|
||||||
caller-supplied `IMalloc` as the allocator for that object's lifetime.
|
|
||||||
|
|
||||||
The `dxc` executable is itself a thin client. It `dlopen`s dxcompiler through
|
|
||||||
`include/dxc/Support/dxcapi.use.h` and drives it with `CLSID_DxcCompiler`,
|
|
||||||
`CLSID_DxcLibrary`, and so on (`tools/clang/tools/dxclib/dxc.cpp`). The command
|
|
||||||
line and the API share one option parser: the arguments passed to
|
|
||||||
`IDxcCompiler3::Compile` are dxc command-line flags as wide strings.
|
|
||||||
|
|
||||||
### Classes and interfaces
|
|
||||||
|
|
||||||
| CLSID | Interfaces it answers `QueryInterface` for | Typical use |
|
|
||||||
|---|---|---|
|
|
||||||
| `CLSID_DxcCompiler` | `IDxcCompiler3`, `IDxcVersionInfo`, `IDxcVersionInfo2/3`, `IDxcLangExtensions*`, `IDxcContainerEvent`; legacy `IDxcCompiler`, `IDxcCompiler2` via an adapter sub-object (`dxcompilerobj.cpp:499`) | compile, preprocess, disassemble |
|
|
||||||
| `CLSID_DxcUtils` == `CLSID_DxcLibrary` (same GUID) | `IDxcUtils`, legacy `IDxcLibrary` | blobs, default include handler, `BuildArguments`, `CreateReflection`, `GetDxilContainerPart` |
|
|
||||||
| `CLSID_DxcCompilerArgs` | `IDxcCompilerArgs` | building argument lists |
|
|
||||||
| `CLSID_DxcValidator` | `IDxcValidator`, `IDxcValidator2`, `IDxcVersionInfo` | validation and signing (also exported by the separate `dxil` library) |
|
|
||||||
| `CLSID_DxcContainerReflection` | `IDxcContainerReflection` | listing container parts, `ID3D12ShaderReflection` |
|
|
||||||
| `CLSID_DxcContainerBuilder` | `IDxcContainerBuilder` | adding and removing parts |
|
|
||||||
| `CLSID_DxcAssembler`, `CLSID_DxcOptimizer`, `CLSID_DxcLinker`, `CLSID_DxcPdbUtils`, `CLSID_DxcRewriter`, `CLSID_DxcIntelliSense` | — | LLVM-IR tooling, PDBs, IntelliSense |
|
|
||||||
|
|
||||||
### Compile contract (`IDxcCompiler3::Compile`, `dxcompilerobj.cpp:517`)
|
|
||||||
|
|
||||||
- Inputs: a `DxcBuffer` (pointer, size, code page; 0 means detect a BOM,
|
|
||||||
otherwise treat as UTF-8), `LPCWSTR` argv, an optional `IDxcIncludeHandler`,
|
|
||||||
and an `riid` that must be `IDxcResult` or `IDxcOperationResult`. Any other
|
|
||||||
`riid`, a null source, or a null argv with `argCount > 0` returns
|
|
||||||
`E_INVALIDARG`.
|
|
||||||
- **Compile errors do not fail the call.** `Compile` returns `S_OK` and the
|
|
||||||
result's `GetStatus` reports `E_FAIL`. The call itself fails only for API
|
|
||||||
misuse or out-of-memory. Clients depend on this.
|
|
||||||
- Outputs are keyed by `DXC_OUT_KIND`: `OBJECT` (DXIL container or SPIR-V
|
|
||||||
words), `ERRORS` (UTF-8 diagnostic text, also present on success when there
|
|
||||||
are warnings), `HLSL` (`-P`), `REFLECTION`, `SHADER_HASH`, `ROOT_SIGNATURE`,
|
|
||||||
`PDB`, and others. Each output can carry a name taken from the flags (`-Fo`,
|
|
||||||
`-Fre`, `-Fsh`, ...). The library never writes files; the client does.
|
|
||||||
- The source name is the first positional argument, or `hlsl.hlsl` if there is
|
|
||||||
none (`dxcompilerobj.cpp:588`). That name appears in diagnostics.
|
|
||||||
- Includes go through a virtual file system (`dxcfilesystem.cpp`). Clang's
|
|
||||||
header search builds each candidate path (including file's directory, then
|
|
||||||
`-I` directories) and passes it through `NormalizePathW` (`Support/Path.h`):
|
|
||||||
`\` becomes `/` on Unix, doubled slashes collapse, and relative paths get a
|
|
||||||
`./` prefix. Each candidate is then handed to `LoadSource`. **A failed
|
|
||||||
`LoadSource` means "try the next candidate", not "abort".** With a null
|
|
||||||
handler, nothing except the main buffer resolves, and DXC never touches the
|
|
||||||
disk itself. `IDxcUtils::CreateDefaultIncludeHandler` is the one that reads
|
|
||||||
from disk (`dxclibrary.cpp:41`).
|
|
||||||
|
|
||||||
## ABI facts libzdxc must match
|
|
||||||
|
|
||||||
These are exactly where a "looks right" reimplementation silently breaks.
|
|
||||||
|
|
||||||
1. **Vtable layout.** On Unix, `IUnknown` has three pure virtuals and *no
|
|
||||||
virtual destructor*. The destructor was removed specifically for ABI
|
|
||||||
(`47f31378a`, #3793). An interface pointer points at a vptr, and the vtable
|
|
||||||
is the base's slots followed by each derived interface's methods in
|
|
||||||
declaration order. This holds on both Itanium and MSVC, so one Zig
|
|
||||||
`extern struct { vtable: *const VTable }` layout serves both.
|
|
||||||
2. **Calling convention.** `STDMETHODCALLTYPE` and `__stdcall` are empty on Unix
|
|
||||||
(plain C convention). On Windows, use `callconv(.winapi)`. Two methods,
|
|
||||||
`IDxcResult::GetOutputByIndex` and `PrimaryOutput`, are declared without
|
|
||||||
`STDMETHODCALLTYPE`. They only differ on 32-bit Windows (`__thiscall`), which
|
|
||||||
can be ignored unless x86-32 is a target.
|
|
||||||
3. **`BOOL` is `bool` (1 byte) on Unix** (`WinAdapter.h:306`) and `int`
|
|
||||||
(4 bytes) on Windows. This affects `IDxcResult::HasOutput`,
|
|
||||||
`IDxcBlobEncoding::GetEncoding(BOOL *)`, and `IDxcPdbUtils::IsFullPDB`.
|
|
||||||
4. **`WCHAR` is `wchar_t`: UTF-32 on Unix, UTF-16 on Windows.** All `LPCWSTR`
|
|
||||||
arguments, file names passed to `LoadSource`, and `IDxcBlobWide` contents
|
|
||||||
follow this. `DXC_CP_WIDE` is `DXC_CP_UTF32` on Unix.
|
|
||||||
5. **`ULONG` is `unsigned long` on Unix** (64-bit on LP64). That is what
|
|
||||||
`AddRef`/`Release` return; in Zig that is `c_ulong`.
|
|
||||||
6. **GUIDs.** `__uuidof` is emulated on the client side through
|
|
||||||
`CROSS_PLATFORM_UUIDOF` templates, so the library only needs to compare
|
|
||||||
16-byte `GUID` values.
|
|
||||||
7. **HRESULTs** use the Windows values: `E_NOINTERFACE` 0x80004002, `E_NOTIMPL`
|
|
||||||
0x80004001, `E_POINTER` 0x80004003, `E_INVALIDARG`, `E_OUTOFMEMORY`,
|
|
||||||
`E_FAIL`, `REGDB_E_CLASSNOTREG`.
|
|
||||||
8. **Ownership.** Every returned interface carries one reference. Reference
|
|
||||||
counts must be atomic: DXC lets separate instances run on separate threads,
|
|
||||||
and clients release objects from any thread. Objects that clients pass in
|
|
||||||
(include handler, blobs) are borrowed; take an `AddRef` only when keeping
|
|
||||||
them.
|
|
||||||
9. **No unwinding across the boundary.** Every exported function and vtable
|
|
||||||
entry must catch every Zig error and turn it into an HRESULT.
|
|
||||||
|
|
||||||
## Proposed shape
|
|
||||||
|
|
||||||
### Layering
|
|
||||||
|
|
||||||
```
|
|
||||||
src/compile.zig Zig-native API: compile(gpa, Request) -> Result
|
|
||||||
Request { source, name, args: []const []const u8, fs: source.FileSystem }
|
|
||||||
Result { status, outputs: [kind]?Output } (bytes + name + code page)
|
|
||||||
src/options.zig dxc argv parser built on options_table (moved out of main.zig)
|
|
||||||
src/capi/ COM layer; the only code that knows about GUIDs and vtables
|
|
||||||
types.zig GUID, HRESULT, BOOL/WCHAR per target, CLSIDs/IIDs from dxcapi.h
|
|
||||||
object.zig Object(Impl, .{ interfaces... }) — atomic refcount, comptime QI table
|
|
||||||
blob.zig IDxcBlob / Encoding / Utf8 / Wide over owned, pinned, or IMalloc memory
|
|
||||||
result.zig IDxcResult + IDxcOperationResult over compile.Result
|
|
||||||
include.zig IDxcIncludeHandler -> source.FileSystem adapter (+ default disk handler)
|
|
||||||
compiler.zig IDxcCompiler3 (+ legacy IDxcCompiler/2 adapter), IDxcVersionInfo
|
|
||||||
utils.zig IDxcUtils, IDxcLibrary, IDxcCompilerArgs
|
|
||||||
exports.zig export fn DxcCreateInstance / DxcCreateInstance2
|
|
||||||
src/main.zig CLI built on compile.zig — the same relationship dxc has with dxcompiler
|
|
||||||
```
|
|
||||||
|
|
||||||
The important split is that `compile.zig` is the real library and `capi/` is a
|
|
||||||
translation shell. The CLI and the COM layer then exercise one code path. Zig
|
|
||||||
users can import the `zdxc` module and call `compile` directly with no COM.
|
|
||||||
|
|
||||||
Existing pieces already fit:
|
|
||||||
|
|
||||||
- `source.FileSystem` is a vtable, so an `IDxcIncludeHandler` adapter is a
|
|
||||||
single `read` implementation. It converts the candidate path to `WCHAR`,
|
|
||||||
calls `LoadSource`, decodes the blob to UTF-8, and maps failure to `null`.
|
|
||||||
The preprocessor must still produce dxc's candidate-path sequence and
|
|
||||||
`NormalizePathW` spelling, because handlers often match on exact strings.
|
|
||||||
Add an oracle test that logs `LoadSource` calls from both libraries.
|
|
||||||
- `Diagnostics.render` already writes to an `Io.Writer`. `DXC_OUT_ERRORS` is
|
|
||||||
that text rendered without color, in dxc's default format.
|
|
||||||
- `DxcCreateInstance2`'s `IMalloc` wraps directly into a `std.mem.Allocator`
|
|
||||||
(`Alloc` / `Realloc` / `Free`), which becomes the `gpa` for that object.
|
|
||||||
|
|
||||||
### Build artifacts
|
|
||||||
|
|
||||||
- `zig build` installs `libzdxc` both as a static library and as a shared
|
|
||||||
library. An option such as `-Ddxcompiler-name` would also name the shared
|
|
||||||
library `libdxcompiler.{so,dylib}` / `dxcompiler.dll`, so existing loaders
|
|
||||||
(`dxcapi.use.h`, hassle-rs, engines that `dlopen` by name) work unmodified.
|
|
||||||
- Optionally, add a `dxil` shim exporting `DxcCreateInstance` for
|
|
||||||
`CLSID_DxcValidator` only. Some clients, such as wgpu through hassle-rs,
|
|
||||||
require `dxil.dll` to load. Since zdxc signs its own output, that validator
|
|
||||||
can re-check the hash and return `S_OK`.
|
|
||||||
- Ship no headers of our own: clients keep using DXC's `dxcapi.h`. The ABI is
|
|
||||||
the contract.
|
|
||||||
|
|
||||||
### Staging
|
|
||||||
|
|
||||||
| Stage | Surface | Who needs it |
|
|
||||||
|---|---|---|
|
|
||||||
| L0 | exports, `IUnknown` machinery, blob family, `IDxcUtils` (`CreateBlob`, `CreateBlobFromPinned`, `LoadFile`, `CreateDefaultIncludeHandler`, `GetBlobAsUtf8`), `IDxcCompiler3::Compile` (no `Disassemble`), `IDxcResult`, `IDxcVersionInfo` | modern engines; enough to run the drop-in oracle |
|
|
||||||
| L1 | legacy `IDxcLibrary`, `IDxcCompiler`/`IDxcCompiler2` (`Compile`, `Preprocess`), `IDxcOperationResult`, `IDxcCompilerArgs`, `IDxcUtils::BuildArguments` | hassle-rs and wgpu, older engines, `-P` users |
|
|
||||||
| L2 | `IDxcContainerReflection` (part listing), `IDxcUtils::GetDxilContainerPart`, `IDxcContainerBuilder`, `IDxcValidator` (hash check) | tooling that inspects containers |
|
|
||||||
| L3 | `IDxcUtils::CreateReflection` / `GetPartReflection` → `ID3D12ShaderReflection` (`d3d12shader.h`) | engines building root signatures from reflection |
|
|
||||||
| — | `Disassemble`, assembler, optimizer, linker, PDB utils, IntelliSense, rewriter, DIA | return `E_NOTIMPL` or `REGDB_E_CLASSNOTREG`, matching the plan's dropped list |
|
|
||||||
|
|
||||||
L3 is the expensive stage. DXC's `ID3D12ShaderReflection` reads the DXIL
|
|
||||||
module from the container's STAT part and walks its metadata, plus RDAT for
|
|
||||||
libraries. zdxc can serve it from bytes it wrote itself, but the reflection
|
|
||||||
interface is large (types, variables, constant buffers, bindings). Because
|
|
||||||
`CreateReflection` takes only a blob, the data must come from the container,
|
|
||||||
not from the compiler's memory. Schedule this alongside M0.1's reflection-match
|
|
||||||
exit criterion. SPIR-V clients use SPIRV-Reflect, not DXC, so it is DXIL-only.
|
|
||||||
|
|
||||||
Versioning: `IDxcVersionInfo::GetVersion` should report the DXC version
|
|
||||||
whose behavior zdxc matches (clients gate features on it), and
|
|
||||||
`IDxcVersionInfo3::GetCustomVersionString` should report `zdxc <version>`.
|
|
||||||
|
|
||||||
## Being a backend for Slang and SDL_shadercross
|
|
||||||
|
|
||||||
Read from Slang `c959b56` (`source/compiler-core/slang-dxc-compiler.cpp`) and
|
|
||||||
SDL_shadercross `1ff05be` (`src/SDL_shadercross.c`,
|
|
||||||
`cmake/FindDirectXShaderCompiler.cmake`). Neither client needs code changes:
|
|
||||||
both reach DXC only through `DxcCreateInstance`, so a library that matches the
|
|
||||||
ABI and is installed under DXC's names is a drop-in replacement. Both feed
|
|
||||||
DXC *machine-generated* HLSL, which makes them good acceptance corpora.
|
|
||||||
|
|
||||||
### SDL_shadercross (smallest surface; best first target)
|
|
||||||
|
|
||||||
- **Linking:** the DXC library is linked at build time (`extern
|
|
||||||
DxcCreateInstance`), not loaded with `dlopen`. CMake finds it either as a
|
|
||||||
vendored DXC subproject or through `FindDirectXShaderCompiler.cmake` with
|
|
||||||
`DirectXShaderCompiler_ROOT`. On non-Windows, that module *requires*
|
|
||||||
`dxcapi.h` in an include directory plus `libdxcompiler` and `libdxil`
|
|
||||||
libraries, even though the C code declares its own vtables and never includes
|
|
||||||
the header. So a zdxc install tree would need `include/dxcapi.h` (a
|
|
||||||
placeholder file would satisfy the lookup), `lib/libdxcompiler.*`, and a
|
|
||||||
`lib/libdxil.*` stub.
|
|
||||||
- **API used:** `CLSID_DxcCompiler`→`IDxcCompiler3::Compile`,
|
|
||||||
`CLSID_DxcUtils`→`IDxcUtils::CreateDefaultIncludeHandler`, and on
|
|
||||||
`IDxcResult`: `GetStatus`, `GetOutput(DXC_OUT_OBJECT, IID_IDxcBlob)`,
|
|
||||||
`GetOutput(DXC_OUT_ERRORS, IID_IDxcBlobUtf8)` (read on success too, for
|
|
||||||
warnings). That is exactly L0.
|
|
||||||
- **Inputs:** `DxcBuffer.Size = strlen + 1`, so **the source buffer includes
|
|
||||||
its NUL terminator**, and the encoding is `DXC_CP_ACP` (0). Arguments are
|
|
||||||
`-D…`, `-E`, `-I <dir>`, `-T {vs,ps,cs}_6_0` only, an optional bare source
|
|
||||||
name, and `-Zi` for debug builds. For SPIR-V: `-spirv
|
|
||||||
-fspv-flatten-resource-arrays -fspv-preserve-interface`, plus
|
|
||||||
`-fspv-preserve-bindings` unless unused bindings are culled, and
|
|
||||||
`-fspv-debug=vulkan-with-source` for debug builds. There is no `-HV`, so
|
|
||||||
dxc's default of 2021 applies.
|
|
||||||
- **Pipeline:** by default, `CompileDXILFromHLSL` **round-trips**:
|
|
||||||
HLSL →(DXC `-spirv`)→ SPIR-V →(SPIRV-Cross, `HLSL_SHADER_MODEL`)→ HLSL
|
|
||||||
→(DXC)→ DXIL. MSL output and all resource reflection come from SPIRV-Cross
|
|
||||||
reading DXC's SPIR-V, and DXC's own reflection is never used. Consequences:
|
|
||||||
- Both backends are on the critical path, and the DXIL backend must accept
|
|
||||||
SPIRV-Cross-generated HLSL.
|
|
||||||
- zdxc's SPIR-V must satisfy SPIRV-Cross, not just `spirv-val`. That means
|
|
||||||
the names, decorations, and interface variables reflection depends on, and
|
|
||||||
the three `-fspv-*` flags above.
|
|
||||||
- No `ID3D12ShaderReflection`, linker, or disassembler is needed.
|
|
||||||
- **Fit with the plan:** vs/ps/cs at 6.0 is inside M0.1. Shadercross is the
|
|
||||||
cheapest real client: L0 plus four `-fspv-*` flags.
|
|
||||||
|
|
||||||
### Slang
|
|
||||||
|
|
||||||
- **Platform gate:** `SLANG_ENABLE_DXIL_SUPPORT` defaults to **0 on Apple
|
|
||||||
platforms**, so stock Slang on macOS never calls dxcompiler. Testing on this
|
|
||||||
Mac needs a Slang build configured with it set to 1, or a Linux/Windows host.
|
|
||||||
- **Loading:** `dlopen("dxcompiler")` (or a path set with
|
|
||||||
`setDownstreamCompilerPath(SLANG_PASS_THROUGH_DXC, …)`). It tries `dxil`
|
|
||||||
first but ignores failure, so no dxil stub is needed.
|
|
||||||
`findFuncByName("DxcCreateInstance")`.
|
|
||||||
- **API used (legacy interfaces, so L1 is required):**
|
|
||||||
- `IDxcCompiler` and `IDxcLibrary::CreateBlobWithEncodingFromPinned`
|
|
||||||
(code page 0).
|
|
||||||
- `IDxcCompiler::Compile(source, name, entry, profile, args, …, includeHandler)`
|
|
||||||
with no defines.
|
|
||||||
- On `IDxcOperationResult`: `GetStatus`, `GetResult`, `GetErrorBuffer`.
|
|
||||||
- It queries `IDxcResult` from the operation result for `DXC_OUT_PDB` only
|
|
||||||
when PDB output is requested.
|
|
||||||
- **Version probing decides the language version.** Slang calls
|
|
||||||
`IDxcVersionInfo::GetVersion`, `IDxcVersionInfo2::GetCommitInfo`, and
|
|
||||||
`IDxcVersionInfo3::GetCustomVersionString`, and adds `-HV 2021` only if the
|
|
||||||
version is ≥ 1.7. The oracle reports `1.11(5583-f9fc72ad)`, so libzdxc should
|
|
||||||
report 1.11. The strings returned by `GetCommitInfo` and
|
|
||||||
`GetCustomVersionString` are freed by the client with `CoTaskMemFree`, which
|
|
||||||
is `free` on Unix (`WinAdapter.h:47`) and `CoTaskMemAlloc` on Windows. **So
|
|
||||||
libzdxc must allocate those with libc `malloc` / `CoTaskMemAlloc`, not a Zig
|
|
||||||
allocator**, which means the shared library links libc.
|
|
||||||
- **Include handler blobs are not real DXC blobs.** Slang's `LoadSource`
|
|
||||||
returns an `ISlangBlob` cast to `IDxcBlob*`. Only `GetBufferPointer` and
|
|
||||||
`GetBufferSize` can be trusted, and `QueryInterface` for `IDxcBlobEncoding`
|
|
||||||
fails. libzdxc must treat such blobs as raw bytes with BOM detection, never
|
|
||||||
assume they are its own blob type, and never downcast. Slang also resolves
|
|
||||||
includes itself from its search directories, so its handler is called with
|
|
||||||
dxc's candidate paths.
|
|
||||||
- **Arguments:** `-Zpr`, `-Gis`, `-denorm <mode>`, `-O0..3`/`-Od`, `-Zi`,
|
|
||||||
`-WX`, `-no-warnings` (always), `-enable-16bit-types`,
|
|
||||||
`-enable/-disable-payload-qualifiers`, plus user pass-through. Profiles
|
|
||||||
cover every stage, including `lib_6_x` for ray tracing.
|
|
||||||
- **Diagnostics:** Slang parses `ERRORS` as clang-style
|
|
||||||
`file:line:col: error|warning: msg`. That is zdxc's `clang` format, which
|
|
||||||
must stay the default for library output.
|
|
||||||
- **Optional extras:**
|
|
||||||
- `IDxcLinker` (`RegisterLibrary` + `Link`), used only when linking
|
|
||||||
precompiled DXIL modules. Slang then compiles the source as `lib_6_x`.
|
|
||||||
- `IDxcCompiler::Disassemble`, used only for `-target dxil-asm`.
|
|
||||||
|
|
||||||
Both are on the plan's dropped list; with them returning
|
|
||||||
`REGDB_E_CLASSNOTREG` / `E_NOTIMPL`, ordinary single-module compiles still
|
|
||||||
work.
|
|
||||||
- **Fit with the plan:** single-entry vs/ps/cs is M0.1. The rest of Slang's
|
|
||||||
stage coverage follows the plan's later milestones (hs/ds, ms/as, then `lib_`
|
|
||||||
at M0.5).
|
|
||||||
|
|
||||||
### Revised staging
|
|
||||||
|
|
||||||
1. **L0 + shadercross acceptance.** Build `test/clients/shadercross.sh`: build
|
|
||||||
shadercross against a zdxc install tree, run its CLI over its test shaders
|
|
||||||
for SPIR-V, DXIL (round-trip), and MSL, and compare with the same run
|
|
||||||
against DXC (DXIL through `dxv`, SPIR-V through `spirv-val`, MSL text
|
|
||||||
directly).
|
|
||||||
2. **L1 + Slang acceptance** on Linux, or a Slang built with
|
|
||||||
`SLANG_ENABLE_DXIL_SUPPORT=1`. Corpus: `slangc -target hlsl` output from
|
|
||||||
Slang's tests, compiled through both libraries.
|
|
||||||
3. Linker and disassembler only if Slang's precompiled-module or `dxil-asm`
|
|
||||||
paths turn out to matter.
|
|
||||||
|
|
||||||
## Testing
|
|
||||||
|
|
||||||
An ABI harness under `test/capi/`, written in C++ and compiled with
|
|
||||||
`zig c++` against the DXC tree's `include/dxc/dxcapi.h` (read in place, not
|
|
||||||
vendored). It `dlopen`s a library by path and runs a fixed script: create each
|
|
||||||
CLSID, query each IID, compile the oracle corpus through `IDxcCompiler3` and
|
|
||||||
the legacy interface, use a logging include handler, and dump status, the
|
|
||||||
output kinds present, error text, and object bytes. Running it against
|
|
||||||
`build/lib/libdxcompiler.dylib` and against libzdxc, then diffing (objects
|
|
||||||
compared through `dxv`, as the CLI oracle already does), gives drop-in
|
|
||||||
compatibility the same oracle treatment as the CLI.
|
|
||||||
|
|
||||||
## Open questions
|
|
||||||
|
|
||||||
- Should `zig build` produce the drop-in name by default, or opt-in only?
|
|
||||||
- Acceptance order: SDL_shadercross first, then Slang (see above). hassle-rs
|
|
||||||
and wgpu also use the legacy interfaces, so L1 for Slang covers them too
|
|
||||||
(not yet verified against hassle-rs source).
|
|
||||||
- Shadercross's lookup needs a `dxcapi.h` to exist. Ship a placeholder, or
|
|
||||||
install DXC's header? Its license (NCSA) allows redistribution, but the
|
|
||||||
project rule only allows vendoring data files.
|
|
||||||
- Does any target need 32-bit Windows? That would force the `__thiscall`
|
|
||||||
handling for the two `IDxcResult` methods.
|
|
||||||
397
src/diag.zig
397
src/diag.zig
|
|
@ -1,85 +1,31 @@
|
||||||
//! Diagnostics: collected during compilation, rendered clang-style (or
|
//! Diagnostics: collected during compilation and rendered clang-style.
|
||||||
//! msvc / vi style) with source snippets, ranges, notes, fix-it hints,
|
|
||||||
//! include chains and macro expansion backtraces.
|
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const Allocator = std.mem.Allocator;
|
const Allocator = std.mem.Allocator;
|
||||||
const source = @import("front/source.zig");
|
const source = @import("front/source.zig");
|
||||||
const Loc = source.Loc;
|
|
||||||
|
|
||||||
pub const Severity = enum {
|
pub const Severity = enum {
|
||||||
note,
|
note,
|
||||||
warning,
|
warning,
|
||||||
@"error",
|
@"error",
|
||||||
fatal,
|
fatal,
|
||||||
|
|
||||||
fn label(s: Severity) []const u8 {
|
|
||||||
return switch (s) {
|
|
||||||
.note => "note",
|
|
||||||
.warning => "warning",
|
|
||||||
.@"error" => "error",
|
|
||||||
.fatal => "fatal error",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
pub const Note = struct {
|
|
||||||
loc: Loc,
|
|
||||||
/// Length in bytes of the highlighted range starting at `loc`.
|
|
||||||
len: u32 = 0,
|
|
||||||
message: []const u8,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const Diagnostic = struct {
|
pub const Diagnostic = struct {
|
||||||
severity: Severity,
|
severity: Severity,
|
||||||
loc: Loc,
|
loc: source.Loc,
|
||||||
len: u32 = 0,
|
|
||||||
message: []const u8,
|
message: []const u8,
|
||||||
/// Warning group, shown as `[-Wgroup]` and controlled by `-Wno-group`.
|
|
||||||
group: ?[]const u8 = null,
|
|
||||||
/// The warning was promoted by -WX.
|
|
||||||
promoted: bool = false,
|
|
||||||
/// Text to insert at `loc` (shown under the caret).
|
|
||||||
fixit: ?[]const u8 = null,
|
|
||||||
notes: std.ArrayList(Note) = .empty,
|
|
||||||
/// Ordering key: diagnostics are rendered sorted by position (stable),
|
|
||||||
/// so preprocessor and parser messages interleave in source order.
|
|
||||||
position: u64 = 0,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub const Report = struct {
|
|
||||||
severity: Severity,
|
|
||||||
loc: Loc,
|
|
||||||
len: u32 = 0,
|
|
||||||
group: ?[]const u8 = null,
|
|
||||||
fixit: ?[]const u8 = null,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const Diagnostics = struct {
|
pub const Diagnostics = struct {
|
||||||
arena: std.heap.ArenaAllocator,
|
arena: std.heap.ArenaAllocator,
|
||||||
list: std.ArrayList(*Diagnostic) = .empty,
|
list: std.ArrayList(Diagnostic) = .empty,
|
||||||
error_count: u32 = 0,
|
error_count: u32 = 0,
|
||||||
warning_count: u32 = 0,
|
warning_count: u32 = 0,
|
||||||
/// -WX
|
/// -WX
|
||||||
warnings_as_errors: bool = false,
|
warnings_as_errors: bool = false,
|
||||||
/// -no-warnings
|
/// -no-warnings
|
||||||
suppress_warnings: bool = false,
|
suppress_warnings: bool = false,
|
||||||
/// Groups disabled with -Wno-<group>.
|
|
||||||
disabled_groups: std.StringHashMapUnmanaged(void) = .empty,
|
|
||||||
/// Render at most this many errors (0 = no limit), like clang's
|
|
||||||
/// -ferror-limit. Applied in source order when rendering.
|
|
||||||
error_limit: u32 = 20,
|
|
||||||
/// Set by producers (preprocessor token count, parser token index)
|
|
||||||
/// and captured by each new diagnostic.
|
|
||||||
position: u64 = 0,
|
|
||||||
/// A fatal error was reported or the error limit reached: producers
|
|
||||||
/// should stop.
|
|
||||||
stopped: bool = false,
|
|
||||||
/// Position at which compilation stopped. Diagnostics for earlier
|
|
||||||
/// positions are still accepted: the preprocessor runs ahead of the
|
|
||||||
/// parser, so a fatal error late in the file must not hide parse
|
|
||||||
/// errors before it.
|
|
||||||
stop_position: u64 = std.math.maxInt(u64),
|
|
||||||
|
|
||||||
pub fn init(gpa: Allocator) Diagnostics {
|
pub fn init(gpa: Allocator) Diagnostics {
|
||||||
return .{ .arena = .init(gpa) };
|
return .{ .arena = .init(gpa) };
|
||||||
|
|
@ -89,338 +35,49 @@ pub const Diagnostics = struct {
|
||||||
d.arena.deinit();
|
d.arena.deinit();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn disableGroup(d: *Diagnostics, group: []const u8) !void {
|
pub fn add(d: *Diagnostics, severity: Severity, loc: source.Loc, comptime fmt: []const u8, args: anytype) void {
|
||||||
const a = d.arena.allocator();
|
var sev = severity;
|
||||||
try d.disabled_groups.put(a, try a.dupe(u8, group), {});
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Report a diagnostic. Returns null when it is suppressed (disabled
|
|
||||||
/// warning, or after the compilation was stopped); otherwise notes can
|
|
||||||
/// be attached to the result with `note`.
|
|
||||||
/// True once compilation has stopped at or before `position`.
|
|
||||||
pub fn stoppedAt(d: *const Diagnostics, position: u64) bool {
|
|
||||||
return d.stopped and position >= d.stop_position;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn report(d: *Diagnostics, r: Report, comptime fmt: []const u8, args: anytype) ?*Diagnostic {
|
|
||||||
if (d.stoppedAt(d.position)) return null;
|
|
||||||
var sev = r.severity;
|
|
||||||
var promoted = false;
|
|
||||||
if (sev == .warning) {
|
if (sev == .warning) {
|
||||||
if (d.suppress_warnings) return null;
|
if (d.suppress_warnings) return;
|
||||||
if (r.group) |g| if (d.disabled_groups.contains(g)) return null;
|
if (d.warnings_as_errors) sev = .@"error";
|
||||||
if (d.warnings_as_errors) {
|
|
||||||
sev = .@"error";
|
|
||||||
promoted = true;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
const a = d.arena.allocator();
|
const a = d.arena.allocator();
|
||||||
const diag = a.create(Diagnostic) catch return null;
|
const msg = std.fmt.allocPrint(a, fmt, args) catch "out of memory formatting diagnostic";
|
||||||
diag.* = .{
|
d.list.append(a, .{ .severity = sev, .loc = loc, .message = msg }) catch return;
|
||||||
.severity = sev,
|
|
||||||
.loc = r.loc,
|
|
||||||
.len = r.len,
|
|
||||||
.message = std.fmt.allocPrint(a, fmt, args) catch "out of memory formatting diagnostic",
|
|
||||||
.group = r.group,
|
|
||||||
.promoted = promoted,
|
|
||||||
.fixit = r.fixit,
|
|
||||||
.position = d.position,
|
|
||||||
};
|
|
||||||
d.list.append(a, diag) catch return null;
|
|
||||||
switch (sev) {
|
switch (sev) {
|
||||||
.@"error" => d.error_count += 1,
|
.@"error", .fatal => d.error_count += 1,
|
||||||
.fatal => {
|
|
||||||
d.error_count += 1;
|
|
||||||
if (!d.stopped or d.position < d.stop_position) d.stop_position = d.position;
|
|
||||||
d.stopped = true;
|
|
||||||
},
|
|
||||||
.warning => d.warning_count += 1,
|
.warning => d.warning_count += 1,
|
||||||
.note => {},
|
.note => {},
|
||||||
}
|
}
|
||||||
return diag;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Attach a note to `diag` (no-op when the diagnostic was suppressed).
|
pub fn err(d: *Diagnostics, loc: source.Loc, comptime fmt: []const u8, args: anytype) void {
|
||||||
pub fn note(d: *Diagnostics, diag: ?*Diagnostic, loc: Loc, len: u32, comptime fmt: []const u8, args: anytype) void {
|
d.add(.@"error", loc, fmt, args);
|
||||||
const target = diag orelse return;
|
|
||||||
const a = d.arena.allocator();
|
|
||||||
const msg = std.fmt.allocPrint(a, fmt, args) catch return;
|
|
||||||
target.notes.append(a, .{ .loc = loc, .len = len, .message = msg }) catch {};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn err(d: *Diagnostics, loc: Loc, comptime fmt: []const u8, args: anytype) void {
|
pub fn warn(d: *Diagnostics, loc: source.Loc, comptime fmt: []const u8, args: anytype) void {
|
||||||
_ = d.report(.{ .severity = .@"error", .loc = loc }, fmt, args);
|
d.add(.warning, loc, fmt, args);
|
||||||
}
|
|
||||||
|
|
||||||
pub fn warn(d: *Diagnostics, loc: Loc, comptime fmt: []const u8, args: anytype) void {
|
|
||||||
_ = d.report(.{ .severity = .warning, .loc = loc }, fmt, args);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Compatibility shim for callers that pass a severity directly.
|
|
||||||
pub fn add(d: *Diagnostics, severity: Severity, loc: Loc, comptime fmt: []const u8, args: anytype) void {
|
|
||||||
_ = d.report(.{ .severity = severity, .loc = loc }, fmt, args);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn hasErrors(d: *const Diagnostics) bool {
|
pub fn hasErrors(d: *const Diagnostics) bool {
|
||||||
return d.error_count != 0;
|
return d.error_count != 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Diagnostics sorted for output (stable by position).
|
/// Render all diagnostics as `file:line:col: error: message` followed by
|
||||||
pub fn sorted(d: *Diagnostics) []const *Diagnostic {
|
/// the source line and a caret.
|
||||||
std.sort.insertion(*Diagnostic, d.list.items, {}, struct {
|
pub fn render(d: *const Diagnostics, sm: *const source.SourceManager, w: *std.Io.Writer) !void {
|
||||||
fn lt(_: void, a: *Diagnostic, b: *Diagnostic) bool {
|
for (d.list.items) |diag| {
|
||||||
return a.position < b.position;
|
if (diag.loc.isNone()) {
|
||||||
}
|
try w.print("{s}: {s}\n", .{ @tagName(diag.severity), diag.message });
|
||||||
}.lt);
|
|
||||||
return d.list.items;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn render(d: *Diagnostics, sm: *const source.SourceManager, w: *std.Io.Writer, style: Style) !void {
|
|
||||||
var r: Renderer = .{ .sm = sm, .w = w, .style = style };
|
|
||||||
var errors: u32 = 0;
|
|
||||||
for (d.sorted()) |diag| {
|
|
||||||
if (diag.severity == .@"error" or diag.severity == .fatal) {
|
|
||||||
if (d.error_limit != 0 and errors == d.error_limit) {
|
|
||||||
try r.message(.fatal, .none, 0, "too many errors emitted, stopping now", null, null);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
errors += 1;
|
|
||||||
}
|
|
||||||
try r.diagnostic(diag);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
pub const Format = enum {
|
|
||||||
/// `file:line:col: error: message`
|
|
||||||
clang,
|
|
||||||
/// `file(line,col): error: message` (clickable in Visual Studio)
|
|
||||||
msvc,
|
|
||||||
/// `file +line:col: error: message`
|
|
||||||
vi,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub const Style = struct {
|
|
||||||
format: Format = .clang,
|
|
||||||
color: bool = false,
|
|
||||||
/// Show source lines, carets and fix-its.
|
|
||||||
snippets: bool = true,
|
|
||||||
};
|
|
||||||
|
|
||||||
const Renderer = struct {
|
|
||||||
sm: *const source.SourceManager,
|
|
||||||
w: *std.Io.Writer,
|
|
||||||
style: Style,
|
|
||||||
/// File of the previous top-level diagnostic, to print include chains
|
|
||||||
/// only when they change (as clang does).
|
|
||||||
last_file: ?source.FileId = null,
|
|
||||||
|
|
||||||
const reset = "\x1b[0m";
|
|
||||||
const bold = "\x1b[1m";
|
|
||||||
|
|
||||||
fn color(r: *Renderer, code: []const u8) !void {
|
|
||||||
if (r.style.color) try r.w.writeAll(code);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn sevColor(sev: Severity) []const u8 {
|
|
||||||
return switch (sev) {
|
|
||||||
.note => "\x1b[1;30m",
|
|
||||||
.warning => "\x1b[1;35m",
|
|
||||||
.@"error", .fatal => "\x1b[1;31m",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
fn diagnostic(r: *Renderer, d: *const Diagnostic) !void {
|
|
||||||
const file_loc = if (d.loc.isNone()) d.loc else r.sm.fileLoc(d.loc);
|
|
||||||
if (!file_loc.isNone()) try r.includeChain(file_loc.file);
|
|
||||||
var group_buf: [128]u8 = undefined;
|
|
||||||
const group: ?[]const u8 = if (d.group) |g|
|
|
||||||
(if (d.promoted)
|
|
||||||
std.fmt.bufPrint(&group_buf, "-Werror,-W{s}", .{g}) catch g
|
|
||||||
else
|
|
||||||
std.fmt.bufPrint(&group_buf, "-W{s}", .{g}) catch g)
|
|
||||||
else
|
|
||||||
null;
|
|
||||||
try r.message(d.severity, d.loc, d.len, d.message, group, d.fixit);
|
|
||||||
try r.macroBacktrace(d.loc);
|
|
||||||
for (d.notes.items) |n| {
|
|
||||||
try r.message(.note, n.loc, n.len, n.message, null, null);
|
|
||||||
try r.macroBacktrace(n.loc);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn includeChain(r: *Renderer, file: source.FileId) !void {
|
|
||||||
if (r.last_file == file) return;
|
|
||||||
r.last_file = file;
|
|
||||||
// Outermost include first, one "In file included from" per level,
|
|
||||||
// matching dxc.
|
|
||||||
var chain: [64]Loc = undefined;
|
|
||||||
var n: usize = 0;
|
|
||||||
var inc = r.sm.file(file).included_from;
|
|
||||||
while (!inc.isNone() and n < chain.len) {
|
|
||||||
chain[n] = inc;
|
|
||||||
n += 1;
|
|
||||||
inc = r.sm.file(r.sm.fileLoc(inc).file).included_from;
|
|
||||||
}
|
|
||||||
while (n > 0) {
|
|
||||||
n -= 1;
|
|
||||||
const p = r.sm.presumedLoc(chain[n]);
|
|
||||||
try r.color(bold);
|
|
||||||
try r.w.print("In file included from {s}:{d}:\n", .{ p.file, p.line });
|
|
||||||
try r.color(reset);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `expanded from macro` notes for each macro level of `loc`,
|
|
||||||
/// outermost first (as dxc prints them); argument levels are skipped.
|
|
||||||
fn macroBacktrace(r: *Renderer, loc: Loc) !void {
|
|
||||||
var levels: [32]*const source.Expansion = undefined;
|
|
||||||
var n: usize = 0;
|
|
||||||
var cur = loc;
|
|
||||||
while (cur.isMacro() and n < levels.len) {
|
|
||||||
const e = r.sm.expansion(cur);
|
|
||||||
if (e.is_arg) {
|
|
||||||
cur = e.spelling;
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
levels[n] = e;
|
const f = sm.file(diag.loc.file);
|
||||||
n += 1;
|
const lc = sm.lineCol(diag.loc);
|
||||||
cur = e.expansion;
|
try w.print("{s}:{d}:{d}: {s}: {s}\n", .{ f.path, lc.line, lc.col, @tagName(diag.severity), diag.message });
|
||||||
}
|
const line = sm.lineText(diag.loc);
|
||||||
while (n > 0) {
|
try w.print("{s}\n", .{line});
|
||||||
n -= 1;
|
for (0..lc.col - 1) |i| try w.writeByte(if (i < line.len and line[i] == '\t') '\t' else ' ');
|
||||||
const e = levels[n];
|
try w.writeAll("^\n");
|
||||||
var buf: [256]u8 = undefined;
|
|
||||||
const msg = std.fmt.bufPrint(&buf, "expanded from macro '{s}'", .{e.macro_name}) catch "expanded from macro";
|
|
||||||
try r.message(.note, r.sm.spellingLoc(e.spelling), 0, msg, null, null);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn message(r: *Renderer, sev: Severity, loc: Loc, len: u32, msg: []const u8, group: ?[]const u8, fixit: ?[]const u8) !void {
|
|
||||||
const w = r.w;
|
|
||||||
try r.color(bold);
|
|
||||||
if (!loc.isNone()) {
|
|
||||||
const p = r.sm.presumedLoc(loc);
|
|
||||||
const col = r.sm.lineCol(loc).col;
|
|
||||||
switch (r.style.format) {
|
|
||||||
.clang => try w.print("{s}:{d}:{d}: ", .{ p.file, p.line, col }),
|
|
||||||
.msvc => try w.print("{s}({d},{d}): ", .{ p.file, p.line, col }),
|
|
||||||
.vi => try w.print("{s} +{d}:{d}: ", .{ p.file, p.line, col }),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
try r.color(sevColor(sev));
|
|
||||||
try w.print("{s}: ", .{sev.label()});
|
|
||||||
try r.color(reset);
|
|
||||||
try r.color(bold);
|
|
||||||
try w.writeAll(msg);
|
|
||||||
if (group) |g| try w.print(" [{s}]", .{g});
|
|
||||||
try r.color(reset);
|
|
||||||
try w.writeByte('\n');
|
|
||||||
if (loc.isNone() or !r.style.snippets) return;
|
|
||||||
try r.snippet(loc, len, fixit);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn snippet(r: *Renderer, loc: Loc, len: u32, fixit: ?[]const u8) !void {
|
|
||||||
const w = r.w;
|
|
||||||
const line = r.sm.lineText(loc);
|
|
||||||
const col = r.sm.lineCol(loc).col;
|
|
||||||
try w.print("{s}\n", .{line});
|
|
||||||
const caret_at = col - 1;
|
|
||||||
// Indentation keeps tabs so the caret lines up with the source.
|
|
||||||
for (0..caret_at) |i| try w.writeByte(if (i < line.len and line[i] == '\t') '\t' else ' ');
|
|
||||||
try r.color("\x1b[1;32m");
|
|
||||||
try w.writeByte('^');
|
|
||||||
if (len > 1) {
|
|
||||||
const end = @min(caret_at + len, line.len);
|
|
||||||
if (end > caret_at + 1) try w.splatByteAll('~', end - caret_at - 1);
|
|
||||||
}
|
|
||||||
try r.color(reset);
|
|
||||||
try w.writeByte('\n');
|
|
||||||
if (fixit) |text| {
|
|
||||||
for (0..caret_at) |i| try w.writeByte(if (i < line.len and line[i] == '\t') '\t' else ' ');
|
|
||||||
try r.color("\x1b[0;32m");
|
|
||||||
try w.writeAll(text);
|
|
||||||
try r.color(reset);
|
|
||||||
try w.writeByte('\n');
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
test "rendering: ranges, notes, fix-its, groups, formats" {
|
|
||||||
const gpa = std.testing.allocator;
|
|
||||||
var mfs: source.MemoryFs = .{};
|
|
||||||
var sm = source.SourceManager.init(gpa, mfs.fileSystem());
|
|
||||||
defer sm.deinit();
|
|
||||||
const f = try sm.addFile("a.hlsl", "float x = foo(1\n\tint y;\n");
|
|
||||||
var d = Diagnostics.init(gpa);
|
|
||||||
defer d.deinit();
|
|
||||||
const e = d.report(.{ .severity = .@"error", .loc = .{ .file = f, .offset = 15 }, .fixit = ")" }, "expected ')'", .{});
|
|
||||||
d.note(e, .{ .file = f, .offset = 13 }, 1, "to match this '('", .{});
|
|
||||||
_ = d.report(.{ .severity = .warning, .loc = .{ .file = f, .offset = 17 }, .len = 3, .group = "demo" }, "suspicious", .{});
|
|
||||||
|
|
||||||
var out: std.Io.Writer.Allocating = .init(gpa);
|
|
||||||
defer out.deinit();
|
|
||||||
try d.render(&sm, &out.writer, .{});
|
|
||||||
try std.testing.expectEqualStrings(
|
|
||||||
\\a.hlsl:1:16: error: expected ')'
|
|
||||||
\\float x = foo(1
|
|
||||||
\\ ^
|
|
||||||
\\ )
|
|
||||||
\\a.hlsl:1:14: note: to match this '('
|
|
||||||
\\float x = foo(1
|
|
||||||
\\ ^
|
|
||||||
\\a.hlsl:2:2: warning: suspicious [-Wdemo]
|
|
||||||
\\
|
|
||||||
++ "\tint y;\n\t^~~\n", out.written());
|
|
||||||
|
|
||||||
var out2: std.Io.Writer.Allocating = .init(gpa);
|
|
||||||
defer out2.deinit();
|
|
||||||
try d.render(&sm, &out2.writer, .{ .format = .msvc, .snippets = false });
|
|
||||||
try std.testing.expectEqualStrings(
|
|
||||||
\\a.hlsl(1,16): error: expected ')'
|
|
||||||
\\a.hlsl(1,14): note: to match this '('
|
|
||||||
\\a.hlsl(2,2): warning: suspicious [-Wdemo]
|
|
||||||
\\
|
|
||||||
, out2.written());
|
|
||||||
}
|
|
||||||
|
|
||||||
test "warning policy and error limit" {
|
|
||||||
const gpa = std.testing.allocator;
|
|
||||||
var d = Diagnostics.init(gpa);
|
|
||||||
defer d.deinit();
|
|
||||||
try d.disableGroup("quiet");
|
|
||||||
try std.testing.expect(d.report(.{ .severity = .warning, .loc = .none, .group = "quiet" }, "x", .{}) == null);
|
|
||||||
d.warnings_as_errors = true;
|
|
||||||
const w = d.report(.{ .severity = .warning, .loc = .none, .group = "loud" }, "y", .{}).?;
|
|
||||||
try std.testing.expectEqual(Severity.@"error", w.severity);
|
|
||||||
d.error_limit = 2;
|
|
||||||
d.err(.none, "e2", .{});
|
|
||||||
d.err(.none, "e3", .{});
|
|
||||||
var mfs: source.MemoryFs = .{};
|
|
||||||
var sm = source.SourceManager.init(gpa, mfs.fileSystem());
|
|
||||||
defer sm.deinit();
|
|
||||||
var out: std.Io.Writer.Allocating = .init(gpa);
|
|
||||||
defer out.deinit();
|
|
||||||
try d.render(&sm, &out.writer, .{});
|
|
||||||
try std.testing.expectEqualStrings(
|
|
||||||
\\error: y [-Werror,-Wloud]
|
|
||||||
\\error: e2
|
|
||||||
\\fatal error: too many errors emitted, stopping now
|
|
||||||
\\
|
|
||||||
, out.written());
|
|
||||||
}
|
|
||||||
|
|
||||||
test "a fatal error hides only what follows it" {
|
|
||||||
const gpa = std.testing.allocator;
|
|
||||||
var d = Diagnostics.init(gpa);
|
|
||||||
defer d.deinit();
|
|
||||||
d.position = 10;
|
|
||||||
d.add(.fatal, .none, "missing include", .{});
|
|
||||||
try std.testing.expect(d.stoppedAt(10) and !d.stoppedAt(9));
|
|
||||||
d.position = 5;
|
|
||||||
d.err(.none, "earlier parse error", .{});
|
|
||||||
d.position = 12;
|
|
||||||
d.err(.none, "later error", .{});
|
|
||||||
try std.testing.expectEqual(@as(usize, 2), d.list.items.len);
|
|
||||||
try std.testing.expectEqualStrings("earlier parse error", d.sorted()[0].message);
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -1,275 +0,0 @@
|
||||||
//! Syntax tree for HLSL 2021. Purely syntactic: names are not resolved and
|
|
||||||
//! types are recorded as written. Nodes live in the parser's arena.
|
|
||||||
|
|
||||||
const std = @import("std");
|
|
||||||
const source = @import("source.zig");
|
|
||||||
pub const Loc = source.Loc;
|
|
||||||
|
|
||||||
/// A possibly qualified name as written: `foo`, `N::foo`, `::foo`.
|
|
||||||
pub const Name = struct {
|
|
||||||
loc: Loc,
|
|
||||||
/// Components without separators; a leading empty component means
|
|
||||||
/// a global-scope `::` prefix.
|
|
||||||
parts: []const []const u8,
|
|
||||||
/// Template arguments per part (`S<T>::value`); empty when no part has
|
|
||||||
/// any, otherwise the same length as `parts`.
|
|
||||||
args: []const []const TemplateArg = &.{},
|
|
||||||
|
|
||||||
pub fn last(n: Name) []const u8 {
|
|
||||||
return n.parts[n.parts.len - 1];
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn isSimple(n: Name, s: []const u8) bool {
|
|
||||||
return n.parts.len == 1 and std.mem.eql(u8, n.parts[0], s);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
pub const TemplateArg = union(enum) {
|
|
||||||
type: *TypeRef,
|
|
||||||
expr: *Expr,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// A type as written: `float4`, `Texture2D<float4>`, `vector<float, 4>`,
|
|
||||||
/// `N::S<T>`. Resolution happens in Sema.
|
|
||||||
pub const TypeRef = struct {
|
|
||||||
loc: Loc,
|
|
||||||
name: Name,
|
|
||||||
args: []const TemplateArg = &.{},
|
|
||||||
/// Array dimensions on type arguments: `StructuredBuffer<float[3]>`.
|
|
||||||
array_dims: []const ?*Expr = &.{},
|
|
||||||
/// `[[...]]` attributes after the type (`__builtin_LinAlgMatrix [[...]]`).
|
|
||||||
attrs: []const Attribute = &.{},
|
|
||||||
/// `unorm` / `snorm` inside resource element types.
|
|
||||||
norm: enum { none, unorm, snorm } = .none,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Storage classes, type qualifiers and parameter / interpolation
|
|
||||||
/// modifiers that may precede a declaration.
|
|
||||||
pub const Qualifiers = packed struct(u64) {
|
|
||||||
@"const": bool = false,
|
|
||||||
static: bool = false,
|
|
||||||
uniform: bool = false,
|
|
||||||
@"extern": bool = false,
|
|
||||||
@"volatile": bool = false,
|
|
||||||
precise: bool = false,
|
|
||||||
groupshared: bool = false,
|
|
||||||
shared: bool = false,
|
|
||||||
in: bool = false,
|
|
||||||
out: bool = false,
|
|
||||||
row_major: bool = false,
|
|
||||||
column_major: bool = false,
|
|
||||||
nointerpolation: bool = false,
|
|
||||||
linear: bool = false,
|
|
||||||
centroid: bool = false,
|
|
||||||
sample: bool = false,
|
|
||||||
noperspective: bool = false,
|
|
||||||
globallycoherent: bool = false,
|
|
||||||
reordercoherent: bool = false,
|
|
||||||
@"inline": bool = false,
|
|
||||||
@"export": bool = false,
|
|
||||||
// Geometry shader input primitive types.
|
|
||||||
point: bool = false,
|
|
||||||
line: bool = false,
|
|
||||||
triangle: bool = false,
|
|
||||||
lineadj: bool = false,
|
|
||||||
triangleadj: bool = false,
|
|
||||||
// Mesh shader output / payload modifiers.
|
|
||||||
vertices: bool = false,
|
|
||||||
indices: bool = false,
|
|
||||||
primitives: bool = false,
|
|
||||||
payload: bool = false,
|
|
||||||
_: u34 = 0,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// `[name(args)]` or `[[ns::name(args)]]`.
|
|
||||||
pub const Attribute = struct {
|
|
||||||
loc: Loc,
|
|
||||||
/// e.g. `numthreads`, `vk::binding`.
|
|
||||||
name: []const u8,
|
|
||||||
args: []const *Expr,
|
|
||||||
double_bracket: bool,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Text after `:` on a declarator.
|
|
||||||
pub const Semantic = struct {
|
|
||||||
loc: Loc,
|
|
||||||
/// `access` is a ray payload qualifier: `read(caller)`, `write(miss)`.
|
|
||||||
kind: enum { semantic, register, packoffset, access },
|
|
||||||
/// Semantic name (`SV_Target0`), or the comma-separated arguments of
|
|
||||||
/// register(...) / packoffset(...) with internal tokens joined
|
|
||||||
/// (`t0`, `space1`, `c0.x`).
|
|
||||||
values: []const []const u8,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub const UnaryOp = enum { plus, minus, not, bit_not, pre_inc, pre_dec, post_inc, post_dec };
|
|
||||||
|
|
||||||
pub const BinaryOp = enum {
|
|
||||||
mul,
|
|
||||||
div,
|
|
||||||
rem,
|
|
||||||
add,
|
|
||||||
sub,
|
|
||||||
shl,
|
|
||||||
shr,
|
|
||||||
lt,
|
|
||||||
gt,
|
|
||||||
le,
|
|
||||||
ge,
|
|
||||||
eq,
|
|
||||||
ne,
|
|
||||||
bit_and,
|
|
||||||
bit_xor,
|
|
||||||
bit_or,
|
|
||||||
log_and,
|
|
||||||
log_or,
|
|
||||||
comma,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub const AssignOp = enum { assign, mul, div, rem, add, sub, shl, shr, bit_and, bit_xor, bit_or };
|
|
||||||
|
|
||||||
pub const Expr = struct {
|
|
||||||
loc: Loc,
|
|
||||||
kind: Kind,
|
|
||||||
|
|
||||||
pub const Kind = union(enum) {
|
|
||||||
int_lit: []const u8,
|
|
||||||
float_lit: []const u8,
|
|
||||||
bool_lit: bool,
|
|
||||||
string_lit: []const u8,
|
|
||||||
name: Name,
|
|
||||||
this,
|
|
||||||
unary: struct { op: UnaryOp, operand: *Expr },
|
|
||||||
binary: struct { op: BinaryOp, lhs: *Expr, rhs: *Expr },
|
|
||||||
assign: struct { op: AssignOp, lhs: *Expr, rhs: *Expr },
|
|
||||||
conditional: struct { cond: *Expr, then: *Expr, @"else": *Expr },
|
|
||||||
/// Function or method call; `template_args` for `f<T>(...)`.
|
|
||||||
call: struct { callee: *Expr, args: []const *Expr, template_args: []const TemplateArg = &.{} },
|
|
||||||
/// Type used as a function: `float4(...)`, `vector<float, 2>(...)`.
|
|
||||||
construct: struct { type: *TypeRef, args: []const *Expr },
|
|
||||||
cast: struct { type: *TypeRef, array_dims: []const ?*Expr = &.{}, operand: *Expr },
|
|
||||||
/// `.name` (field, swizzle or method); `arrow` is accepted for
|
|
||||||
/// error reporting.
|
|
||||||
member: struct { base: *Expr, name: []const u8, name_loc: Loc },
|
|
||||||
index: struct { base: *Expr, index: *Expr },
|
|
||||||
init_list: []const *Expr,
|
|
||||||
sizeof_type: *TypeRef,
|
|
||||||
sizeof_expr: *Expr,
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
pub const Stmt = struct {
|
|
||||||
loc: Loc,
|
|
||||||
attrs: []const Attribute = &.{},
|
|
||||||
kind: Kind,
|
|
||||||
|
|
||||||
pub const Kind = union(enum) {
|
|
||||||
compound: []const *Stmt,
|
|
||||||
/// Local declarations: variables, typedefs, structs.
|
|
||||||
decl: []const *Decl,
|
|
||||||
expr: *Expr,
|
|
||||||
empty,
|
|
||||||
/// `cond_decl` is set for `if (T x = e)`; `cond` then names `x`.
|
|
||||||
@"if": struct { cond_decl: ?*Decl = null, cond: *Expr, then: *Stmt, @"else": ?*Stmt },
|
|
||||||
@"for": struct { init: ?*Stmt, cond: ?*Expr, inc: ?*Expr, body: *Stmt },
|
|
||||||
@"while": struct { cond_decl: ?*Decl = null, cond: *Expr, body: *Stmt },
|
|
||||||
do_while: struct { body: *Stmt, cond: *Expr },
|
|
||||||
@"switch": struct { cond_decl: ?*Decl = null, cond: *Expr, body: *Stmt },
|
|
||||||
case: struct { value: *Expr, stmt: *Stmt },
|
|
||||||
default: *Stmt,
|
|
||||||
@"break",
|
|
||||||
@"continue",
|
|
||||||
@"return": ?*Expr,
|
|
||||||
discard,
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
pub const VarDecl = struct {
|
|
||||||
attrs: []const Attribute,
|
|
||||||
/// Non-empty for variable templates.
|
|
||||||
template_params: []const TemplateParam = &.{},
|
|
||||||
/// Qualified out-of-line definitions (`int S::x = 1;`) keep the full
|
|
||||||
/// spelled name, e.g. `S::x`.
|
|
||||||
quals: Qualifiers,
|
|
||||||
type: *TypeRef,
|
|
||||||
name: []const u8,
|
|
||||||
name_loc: Loc,
|
|
||||||
array_dims: []const ?*Expr,
|
|
||||||
semantics: []const Semantic,
|
|
||||||
bitfield: ?*Expr = null,
|
|
||||||
init: ?*Expr = null,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub const TemplateParam = struct {
|
|
||||||
loc: Loc,
|
|
||||||
name: []const u8,
|
|
||||||
/// null for `typename T` / `class T`; the type for value parameters.
|
|
||||||
value_type: ?*TypeRef,
|
|
||||||
default: ?TemplateArg,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub const FuncDecl = struct {
|
|
||||||
attrs: []const Attribute,
|
|
||||||
quals: Qualifiers,
|
|
||||||
template_params: []const TemplateParam,
|
|
||||||
ret: *TypeRef,
|
|
||||||
/// Function name; for operators `operator+`, `operator[]`, `operator()`.
|
|
||||||
name: Name,
|
|
||||||
params: []const VarDecl,
|
|
||||||
ret_semantics: []const Semantic,
|
|
||||||
/// Array dimensions after the parameter list (`T f()[N]`).
|
|
||||||
ret_dims: []const ?*Expr = &.{},
|
|
||||||
/// Trailing `const` on methods.
|
|
||||||
is_const: bool,
|
|
||||||
body: ?*Stmt,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub const StructDecl = struct {
|
|
||||||
attrs: []const Attribute,
|
|
||||||
keyword: enum { @"struct", class, interface },
|
|
||||||
template_params: []const TemplateParam,
|
|
||||||
name: ?[]const u8,
|
|
||||||
/// Arguments of a partial / explicit specialization: `S<true, T>`.
|
|
||||||
specialization_args: []const TemplateArg = &.{},
|
|
||||||
bases: []const *TypeRef,
|
|
||||||
/// Null for a forward declaration.
|
|
||||||
members: ?[]const *Decl,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub const CBufferDecl = struct {
|
|
||||||
tbuffer: bool,
|
|
||||||
name: []const u8,
|
|
||||||
semantics: []const Semantic,
|
|
||||||
members: []const *Decl,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub const EnumDecl = struct {
|
|
||||||
name: ?[]const u8,
|
|
||||||
scoped: bool,
|
|
||||||
underlying: ?*TypeRef,
|
|
||||||
values: []const struct { loc: Loc, name: []const u8, value: ?*Expr },
|
|
||||||
};
|
|
||||||
|
|
||||||
pub const Decl = struct {
|
|
||||||
loc: Loc,
|
|
||||||
kind: Kind,
|
|
||||||
|
|
||||||
pub const Kind = union(enum) {
|
|
||||||
@"var": VarDecl,
|
|
||||||
func: FuncDecl,
|
|
||||||
@"struct": StructDecl,
|
|
||||||
cbuffer: CBufferDecl,
|
|
||||||
typedef: struct { name: []const u8, type: *TypeRef, array_dims: []const ?*Expr, template_params: []const TemplateParam = &.{} },
|
|
||||||
@"enum": EnumDecl,
|
|
||||||
namespace: struct { name: []const u8, decls: []const *Decl },
|
|
||||||
/// `using namespace N;`
|
|
||||||
using_namespace: Name,
|
|
||||||
/// `using N::name;`
|
|
||||||
using_decl: Name,
|
|
||||||
pragma: []const u8,
|
|
||||||
static_assert: struct { cond: *Expr, message: ?[]const u8 },
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
pub const TranslationUnit = struct {
|
|
||||||
decls: []const *Decl,
|
|
||||||
};
|
|
||||||
|
|
@ -1,414 +0,0 @@
|
||||||
//! Compact S-expression dump of the AST, for tests and debugging.
|
|
||||||
|
|
||||||
const std = @import("std");
|
|
||||||
const ast = @import("ast.zig");
|
|
||||||
const W = std.Io.Writer;
|
|
||||||
|
|
||||||
pub fn dumpUnit(w: *W, tu: ast.TranslationUnit) W.Error!void {
|
|
||||||
for (tu.decls) |d| {
|
|
||||||
try decl(w, d, 0);
|
|
||||||
try w.writeByte('\n');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn indent(w: *W, n: usize) W.Error!void {
|
|
||||||
try w.splatByteAll(' ', n * 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn name(w: *W, n: ast.Name) W.Error!void {
|
|
||||||
for (n.parts, 0..) |part, i| {
|
|
||||||
if (i > 0) try w.writeAll("::");
|
|
||||||
try w.writeAll(part);
|
|
||||||
if (n.args.len > 0 and n.args[i].len > 0) try templateArgs(w, n.args[i]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn templateArgs(w: *W, args: []const ast.TemplateArg) W.Error!void {
|
|
||||||
try w.writeByte('<');
|
|
||||||
for (args, 0..) |a, i| {
|
|
||||||
if (i > 0) try w.writeAll(", ");
|
|
||||||
switch (a) {
|
|
||||||
.type => |ty| try typeRef(w, ty),
|
|
||||||
.expr => |e| try expr(w, e),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
try w.writeByte('>');
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn typeRef(w: *W, t: *const ast.TypeRef) W.Error!void {
|
|
||||||
if (t.norm != .none) try w.print("{s} ", .{@tagName(t.norm)});
|
|
||||||
try name(w, t.name);
|
|
||||||
if (t.args.len > 0) try templateArgs(w, t.args);
|
|
||||||
try dims(w, t.array_dims);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn quals(w: *W, q: ast.Qualifiers) W.Error!void {
|
|
||||||
const info = @typeInfo(ast.Qualifiers).@"struct";
|
|
||||||
inline for (info.field_names, info.field_types) |fname, ftype| {
|
|
||||||
if (ftype == bool and @field(q, fname)) try w.print("{s} ", .{fname});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn attrs(w: *W, list: []const ast.Attribute) W.Error!void {
|
|
||||||
for (list) |a| {
|
|
||||||
try w.print("[{s}", .{a.name});
|
|
||||||
if (a.args.len > 0) {
|
|
||||||
try w.writeByte('(');
|
|
||||||
for (a.args, 0..) |e, i| {
|
|
||||||
if (i > 0) try w.writeAll(", ");
|
|
||||||
try expr(w, e);
|
|
||||||
}
|
|
||||||
try w.writeByte(')');
|
|
||||||
}
|
|
||||||
try w.writeAll("] ");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn semantics(w: *W, list: []const ast.Semantic) W.Error!void {
|
|
||||||
for (list) |s| {
|
|
||||||
switch (s.kind) {
|
|
||||||
.semantic => try w.print(" : {s}", .{s.values[0]}),
|
|
||||||
.register, .packoffset, .access => {
|
|
||||||
try w.print(" : {s}(", .{@tagName(s.kind)});
|
|
||||||
for (s.values, 0..) |v, i| {
|
|
||||||
if (i > 0) try w.writeAll(", ");
|
|
||||||
try w.writeAll(v);
|
|
||||||
}
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn dims(w: *W, list: []const ?*ast.Expr) W.Error!void {
|
|
||||||
for (list) |d| {
|
|
||||||
try w.writeByte('[');
|
|
||||||
if (d) |e| try expr(w, e);
|
|
||||||
try w.writeByte(']');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn varDecl(w: *W, v: ast.VarDecl) W.Error!void {
|
|
||||||
try templateParams(w, v.template_params);
|
|
||||||
try attrs(w, v.attrs);
|
|
||||||
try quals(w, v.quals);
|
|
||||||
try typeRef(w, v.type);
|
|
||||||
try w.print(" {s}", .{v.name});
|
|
||||||
try dims(w, v.array_dims);
|
|
||||||
if (v.bitfield) |b| {
|
|
||||||
try w.writeAll(" : ");
|
|
||||||
try expr(w, b);
|
|
||||||
}
|
|
||||||
try semantics(w, v.semantics);
|
|
||||||
if (v.init) |e| {
|
|
||||||
try w.writeAll(" = ");
|
|
||||||
try expr(w, e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn templateParams(w: *W, params: []const ast.TemplateParam) W.Error!void {
|
|
||||||
if (params.len == 0) return;
|
|
||||||
try w.writeAll("template<");
|
|
||||||
for (params, 0..) |tp, i| {
|
|
||||||
if (i > 0) try w.writeAll(", ");
|
|
||||||
if (tp.value_type) |vt| {
|
|
||||||
try typeRef(w, vt);
|
|
||||||
try w.print(" {s}", .{tp.name});
|
|
||||||
} else try w.print("typename {s}", .{tp.name});
|
|
||||||
}
|
|
||||||
try w.writeAll("> ");
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn decl(w: *W, d: *const ast.Decl, depth: usize) W.Error!void {
|
|
||||||
try indent(w, depth);
|
|
||||||
switch (d.kind) {
|
|
||||||
.@"var" => |v| {
|
|
||||||
try w.writeAll("(var ");
|
|
||||||
try varDecl(w, v);
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
.func => |f| {
|
|
||||||
try w.writeAll("(func ");
|
|
||||||
try templateParams(w, f.template_params);
|
|
||||||
try attrs(w, f.attrs);
|
|
||||||
try quals(w, f.quals);
|
|
||||||
try typeRef(w, f.ret);
|
|
||||||
try w.writeByte(' ');
|
|
||||||
try name(w, f.name);
|
|
||||||
try w.writeByte('(');
|
|
||||||
for (f.params, 0..) |prm, i| {
|
|
||||||
if (i > 0) try w.writeAll(", ");
|
|
||||||
try varDecl(w, prm);
|
|
||||||
}
|
|
||||||
try w.writeByte(')');
|
|
||||||
try dims(w, f.ret_dims);
|
|
||||||
if (f.is_const) try w.writeAll(" const");
|
|
||||||
try semantics(w, f.ret_semantics);
|
|
||||||
if (f.body) |b| {
|
|
||||||
try w.writeByte('\n');
|
|
||||||
try stmt(w, b, depth + 1);
|
|
||||||
}
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
.@"struct" => |s| {
|
|
||||||
try w.print("({s} ", .{@tagName(s.keyword)});
|
|
||||||
try templateParams(w, s.template_params);
|
|
||||||
try attrs(w, s.attrs);
|
|
||||||
try w.writeAll(s.name orelse "<anon>");
|
|
||||||
if (s.specialization_args.len > 0) try templateArgs(w, s.specialization_args);
|
|
||||||
for (s.bases) |b| {
|
|
||||||
try w.writeAll(" : ");
|
|
||||||
try typeRef(w, b);
|
|
||||||
}
|
|
||||||
if (s.members) |members| {
|
|
||||||
for (members) |m| {
|
|
||||||
try w.writeByte('\n');
|
|
||||||
try decl(w, m, depth + 1);
|
|
||||||
}
|
|
||||||
} else try w.writeAll(" <fwd>");
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
.cbuffer => |c| {
|
|
||||||
try w.print("({s} {s}", .{ if (c.tbuffer) "tbuffer" else "cbuffer", c.name });
|
|
||||||
try semantics(w, c.semantics);
|
|
||||||
for (c.members) |m| {
|
|
||||||
try w.writeByte('\n');
|
|
||||||
try decl(w, m, depth + 1);
|
|
||||||
}
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
.typedef => |t| {
|
|
||||||
try w.writeAll("(typedef ");
|
|
||||||
try templateParams(w, t.template_params);
|
|
||||||
try typeRef(w, t.type);
|
|
||||||
try w.print(" {s}", .{t.name});
|
|
||||||
try dims(w, t.array_dims);
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
.@"enum" => |e| {
|
|
||||||
try w.print("(enum{s} {s}", .{ if (e.scoped) " class" else "", e.name orelse "<anon>" });
|
|
||||||
for (e.values) |v| {
|
|
||||||
try w.print(" {s}", .{v.name});
|
|
||||||
if (v.value) |x| {
|
|
||||||
try w.writeByte('=');
|
|
||||||
try expr(w, x);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
.namespace => |n| {
|
|
||||||
try w.print("(namespace {s}", .{n.name});
|
|
||||||
for (n.decls) |m| {
|
|
||||||
try w.writeByte('\n');
|
|
||||||
try decl(w, m, depth + 1);
|
|
||||||
}
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
.using_namespace => |n| {
|
|
||||||
try w.writeAll("(using namespace ");
|
|
||||||
try name(w, n);
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
.using_decl => |n| {
|
|
||||||
try w.writeAll("(using ");
|
|
||||||
try name(w, n);
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
.pragma => |p| try w.print("(pragma {s})", .{p}),
|
|
||||||
.static_assert => |s| {
|
|
||||||
try w.writeAll("(static_assert ");
|
|
||||||
try expr(w, s.cond);
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn stmt(w: *W, s: *const ast.Stmt, depth: usize) W.Error!void {
|
|
||||||
try indent(w, depth);
|
|
||||||
try attrs(w, s.attrs);
|
|
||||||
switch (s.kind) {
|
|
||||||
.compound => |list| {
|
|
||||||
try w.writeAll("{");
|
|
||||||
for (list) |c| {
|
|
||||||
try w.writeByte('\n');
|
|
||||||
try stmt(w, c, depth + 1);
|
|
||||||
}
|
|
||||||
try w.writeAll("}");
|
|
||||||
},
|
|
||||||
.decl => |list| {
|
|
||||||
for (list, 0..) |d, i| {
|
|
||||||
if (i > 0) try w.writeByte('\n');
|
|
||||||
try decl(w, d, if (i == 0) 0 else depth);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
.expr => |e| try expr(w, e),
|
|
||||||
.empty => try w.writeAll("(empty)"),
|
|
||||||
.@"if" => |x| {
|
|
||||||
try w.writeAll("(if ");
|
|
||||||
if (x.cond_decl) |d| {
|
|
||||||
try decl(w, d, 0);
|
|
||||||
try w.writeByte(' ');
|
|
||||||
}
|
|
||||||
try expr(w, x.cond);
|
|
||||||
try w.writeByte('\n');
|
|
||||||
try stmt(w, x.then, depth + 1);
|
|
||||||
if (x.@"else") |e| {
|
|
||||||
try w.writeByte('\n');
|
|
||||||
try stmt(w, e, depth + 1);
|
|
||||||
}
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
.@"for" => |x| {
|
|
||||||
try w.writeAll("(for ");
|
|
||||||
if (x.init) |i| try stmt(w, i, 0) else try w.writeAll("-");
|
|
||||||
try w.writeAll("; ");
|
|
||||||
if (x.cond) |c| try expr(w, c) else try w.writeAll("-");
|
|
||||||
try w.writeAll("; ");
|
|
||||||
if (x.inc) |c| try expr(w, c) else try w.writeAll("-");
|
|
||||||
try w.writeByte('\n');
|
|
||||||
try stmt(w, x.body, depth + 1);
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
.@"while" => |x| {
|
|
||||||
try w.writeAll("(while ");
|
|
||||||
try expr(w, x.cond);
|
|
||||||
try w.writeByte('\n');
|
|
||||||
try stmt(w, x.body, depth + 1);
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
.do_while => |x| {
|
|
||||||
try w.writeAll("(do\n");
|
|
||||||
try stmt(w, x.body, depth + 1);
|
|
||||||
try w.writeAll(" while ");
|
|
||||||
try expr(w, x.cond);
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
.@"switch" => |x| {
|
|
||||||
try w.writeAll("(switch ");
|
|
||||||
try expr(w, x.cond);
|
|
||||||
try w.writeByte('\n');
|
|
||||||
try stmt(w, x.body, depth + 1);
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
.case => |x| {
|
|
||||||
try w.writeAll("(case ");
|
|
||||||
try expr(w, x.value);
|
|
||||||
try w.writeByte('\n');
|
|
||||||
try stmt(w, x.stmt, depth + 1);
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
.default => |x| {
|
|
||||||
try w.writeAll("(default\n");
|
|
||||||
try stmt(w, x, depth + 1);
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
.@"break" => try w.writeAll("(break)"),
|
|
||||||
.@"continue" => try w.writeAll("(continue)"),
|
|
||||||
.discard => try w.writeAll("(discard)"),
|
|
||||||
.@"return" => |v| {
|
|
||||||
try w.writeAll("(return");
|
|
||||||
if (v) |e| {
|
|
||||||
try w.writeByte(' ');
|
|
||||||
try expr(w, e);
|
|
||||||
}
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn expr(w: *W, e: *const ast.Expr) W.Error!void {
|
|
||||||
switch (e.kind) {
|
|
||||||
.int_lit, .float_lit, .string_lit => |t| try w.writeAll(t),
|
|
||||||
.bool_lit => |b| try w.writeAll(if (b) "true" else "false"),
|
|
||||||
.name => |n| try name(w, n),
|
|
||||||
.this => try w.writeAll("this"),
|
|
||||||
.unary => |u| {
|
|
||||||
try w.print("({s} ", .{@tagName(u.op)});
|
|
||||||
try expr(w, u.operand);
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
.binary => |b| {
|
|
||||||
try w.print("({s} ", .{@tagName(b.op)});
|
|
||||||
try expr(w, b.lhs);
|
|
||||||
try w.writeByte(' ');
|
|
||||||
try expr(w, b.rhs);
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
.assign => |a| {
|
|
||||||
try w.print("({s}= ", .{if (a.op == .assign) "" else @tagName(a.op)});
|
|
||||||
try expr(w, a.lhs);
|
|
||||||
try w.writeByte(' ');
|
|
||||||
try expr(w, a.rhs);
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
.conditional => |c| {
|
|
||||||
try w.writeAll("(? ");
|
|
||||||
try expr(w, c.cond);
|
|
||||||
try w.writeByte(' ');
|
|
||||||
try expr(w, c.then);
|
|
||||||
try w.writeByte(' ');
|
|
||||||
try expr(w, c.@"else");
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
.call => |c| {
|
|
||||||
try w.writeAll("(call ");
|
|
||||||
try expr(w, c.callee);
|
|
||||||
if (c.template_args.len > 0) {
|
|
||||||
const tmp: ast.TypeRef = .{ .loc = e.loc, .name = .{ .loc = e.loc, .parts = &.{""} }, .args = c.template_args };
|
|
||||||
try typeRef(w, &tmp);
|
|
||||||
}
|
|
||||||
for (c.args) |a| {
|
|
||||||
try w.writeByte(' ');
|
|
||||||
try expr(w, a);
|
|
||||||
}
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
.construct => |c| {
|
|
||||||
try w.writeAll("(construct ");
|
|
||||||
try typeRef(w, c.type);
|
|
||||||
for (c.args) |a| {
|
|
||||||
try w.writeByte(' ');
|
|
||||||
try expr(w, a);
|
|
||||||
}
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
.cast => |c| {
|
|
||||||
try w.writeAll("(cast ");
|
|
||||||
try typeRef(w, c.type);
|
|
||||||
try dims(w, c.array_dims);
|
|
||||||
try w.writeByte(' ');
|
|
||||||
try expr(w, c.operand);
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
.member => |m| {
|
|
||||||
try w.writeAll("(. ");
|
|
||||||
try expr(w, m.base);
|
|
||||||
try w.print(" {s})", .{m.name});
|
|
||||||
},
|
|
||||||
.index => |x| {
|
|
||||||
try w.writeAll("([] ");
|
|
||||||
try expr(w, x.base);
|
|
||||||
try w.writeByte(' ');
|
|
||||||
try expr(w, x.index);
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
.init_list => |list| {
|
|
||||||
try w.writeByte('{');
|
|
||||||
for (list, 0..) |a, i| {
|
|
||||||
if (i > 0) try w.writeAll(", ");
|
|
||||||
try expr(w, a);
|
|
||||||
}
|
|
||||||
try w.writeByte('}');
|
|
||||||
},
|
|
||||||
.sizeof_type => |t| {
|
|
||||||
try w.writeAll("(sizeof ");
|
|
||||||
try typeRef(w, t);
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
.sizeof_expr => |x| {
|
|
||||||
try w.writeAll("(sizeof ");
|
|
||||||
try expr(w, x);
|
|
||||||
try w.writeByte(')');
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -80,9 +80,7 @@ pub const Flags = packed struct(u8) {
|
||||||
space: bool = false,
|
space: bool = false,
|
||||||
/// Painted by the preprocessor: never macro-expand this identifier.
|
/// Painted by the preprocessor: never macro-expand this identifier.
|
||||||
no_expand: bool = false,
|
no_expand: bool = false,
|
||||||
/// Transient, during macro substitution: the token came from an argument.
|
_: u5 = 0,
|
||||||
from_arg: bool = false,
|
|
||||||
_: u4 = 0,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const Token = struct {
|
pub const Token = struct {
|
||||||
|
|
@ -97,9 +95,8 @@ pub const Token = struct {
|
||||||
return t.kind == kind;
|
return t.kind == kind;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub inline fn isIdent(t: Token, name: []const u8) bool {
|
pub fn isIdent(t: Token, name: []const u8) bool {
|
||||||
// Length first: most keyword checks fail on it without a call.
|
return t.kind == .identifier and std.mem.eql(u8, t.text, name);
|
||||||
return t.kind == .identifier and t.text.len == name.len and std.mem.eql(u8, t.text, name);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
||||||
2087
src/front/parser.zig
2087
src/front/parser.zig
File diff suppressed because it is too large
Load Diff
|
|
@ -8,7 +8,6 @@ const Allocator = std.mem.Allocator;
|
||||||
const source = @import("source.zig");
|
const source = @import("source.zig");
|
||||||
const lexer = @import("lexer.zig");
|
const lexer = @import("lexer.zig");
|
||||||
const Diagnostics = @import("../diag.zig").Diagnostics;
|
const Diagnostics = @import("../diag.zig").Diagnostics;
|
||||||
const Report = @import("../diag.zig").Report;
|
|
||||||
const Token = lexer.Token;
|
const Token = lexer.Token;
|
||||||
const Kind = lexer.Kind;
|
const Kind = lexer.Kind;
|
||||||
const Loc = source.Loc;
|
const Loc = source.Loc;
|
||||||
|
|
@ -120,9 +119,16 @@ const IncludeFrame = struct {
|
||||||
cond_base: usize,
|
cond_base: usize,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const LineOverride = struct {
|
||||||
|
/// Physical line of the #line directive.
|
||||||
|
phys_line: u32,
|
||||||
|
line: u32,
|
||||||
|
name: ?[]const u8,
|
||||||
|
};
|
||||||
|
|
||||||
pub const Error = Allocator.Error;
|
pub const Error = Allocator.Error;
|
||||||
|
|
||||||
pub const PresumedLoc = source.PresumedLoc;
|
pub const PresumedLoc = struct { file: []const u8, line: u32 };
|
||||||
|
|
||||||
const max_include_depth = 200;
|
const max_include_depth = 200;
|
||||||
/// Nesting limit for macro-argument pre-expansion (`F(F(F(...)))`) and for
|
/// Nesting limit for macro-argument pre-expansion (`F(F(F(...)))`) and for
|
||||||
|
|
@ -146,6 +152,7 @@ pub const Preprocessor = struct {
|
||||||
conds: std.ArrayList(Cond) = .empty,
|
conds: std.ArrayList(Cond) = .empty,
|
||||||
pushback: std.ArrayList(Raw) = .empty,
|
pushback: std.ArrayList(Raw) = .empty,
|
||||||
pragma_once: std.StringHashMapUnmanaged(void) = .empty,
|
pragma_once: std.StringHashMapUnmanaged(void) = .empty,
|
||||||
|
line_overrides: std.AutoHashMapUnmanaged(source.FileId, std.ArrayList(LineOverride)) = .empty,
|
||||||
counter: u32 = 0,
|
counter: u32 = 0,
|
||||||
main_file: ?source.FileId = null,
|
main_file: ?source.FileId = null,
|
||||||
isolated_depth: u32 = 0,
|
isolated_depth: u32 = 0,
|
||||||
|
|
@ -181,11 +188,6 @@ pub const Preprocessor = struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn enterFileId(pp: *Preprocessor, id: source.FileId) !void {
|
fn enterFileId(pp: *Preprocessor, id: source.FileId) !void {
|
||||||
return pp.enterFileFrom(id, .none);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn enterFileFrom(pp: *Preprocessor, id: source.FileId, included_from: Loc) !void {
|
|
||||||
pp.sm.setIncludedFrom(id, included_from);
|
|
||||||
const f = pp.sm.file(id);
|
const f = pp.sm.file(id);
|
||||||
try pp.includes.append(pp.arena, .{
|
try pp.includes.append(pp.arena, .{
|
||||||
.lex = .init(f.text, id),
|
.lex = .init(f.text, id),
|
||||||
|
|
@ -267,8 +269,6 @@ pub const Preprocessor = struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn lexRaw(pp: *Preprocessor) Error!Raw {
|
fn lexRaw(pp: *Preprocessor) Error!Raw {
|
||||||
// After a fatal error (or too many errors) nothing more is produced.
|
|
||||||
if (pp.diags.stopped) return .{ .tok = .{ .kind = .eof, .text = "", .loc = .none }, .from_file = true };
|
|
||||||
if (pp.pushback.pop()) |r| return r;
|
if (pp.pushback.pop()) |r| return r;
|
||||||
while (pp.contexts.items.len > 0) {
|
while (pp.contexts.items.len > 0) {
|
||||||
const ctx = &pp.contexts.items[pp.contexts.items.len - 1];
|
const ctx = &pp.contexts.items[pp.contexts.items.len - 1];
|
||||||
|
|
@ -282,7 +282,7 @@ pub const Preprocessor = struct {
|
||||||
}
|
}
|
||||||
while (pp.includes.items.len > 0) {
|
while (pp.includes.items.len > 0) {
|
||||||
const frame = &pp.includes.items[pp.includes.items.len - 1];
|
const frame = &pp.includes.items[pp.includes.items.len - 1];
|
||||||
const t = @call(.always_inline, lexer.Lexer.next, .{&frame.lex});
|
const t = frame.lex.next();
|
||||||
if (t.kind != .eof) return .{ .tok = t, .from_file = true };
|
if (t.kind != .eof) return .{ .tok = t, .from_file = true };
|
||||||
// End of file: diagnose unterminated conditionals, pop.
|
// End of file: diagnose unterminated conditionals, pop.
|
||||||
while (pp.conds.items.len > frame.cond_base) {
|
while (pp.conds.items.len > frame.cond_base) {
|
||||||
|
|
@ -316,7 +316,7 @@ pub const Preprocessor = struct {
|
||||||
const r = try pp.lexRawSkipDirectives();
|
const r = try pp.lexRawSkipDirectives();
|
||||||
const t = r.tok;
|
const t = r.tok;
|
||||||
if (t.kind != .identifier or t.flags.no_expand) return t;
|
if (t.kind != .identifier or t.flags.no_expand) return t;
|
||||||
if (t.text.len == 7 and t.text[0] == '_' and std.mem.eql(u8, t.text, "_Pragma")) {
|
if (std.mem.eql(u8, t.text, "_Pragma")) {
|
||||||
if (try pp.pragmaOperator(t)) |pragma| return pragma;
|
if (try pp.pragmaOperator(t)) |pragma| return pragma;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
@ -358,11 +358,7 @@ pub const Preprocessor = struct {
|
||||||
|
|
||||||
const result = try pp.substitute(m, args);
|
const result = try pp.substitute(m, args);
|
||||||
for (result, 0..) |*t, i| {
|
for (result, 0..) |*t, i| {
|
||||||
// Each expanded token gets a macro location recording where it
|
t.loc = name.loc;
|
||||||
// was spelled and which expansion produced it.
|
|
||||||
const is_arg = t.flags.from_arg;
|
|
||||||
t.flags.from_arg = false;
|
|
||||||
t.loc = try pp.sm.addExpansion(.{ .spelling = t.loc, .expansion = name.loc, .macro_name = m.name, .is_arg = is_arg });
|
|
||||||
if (i == 0) {
|
if (i == 0) {
|
||||||
t.flags.space = name.flags.space;
|
t.flags.space = name.flags.space;
|
||||||
t.flags.bol = name.flags.bol;
|
t.flags.bol = name.flags.bol;
|
||||||
|
|
@ -394,7 +390,7 @@ pub const Preprocessor = struct {
|
||||||
if (std.mem.eql(u8, body, "once")) {
|
if (std.mem.eql(u8, body, "once")) {
|
||||||
const file = pp.currentLexer().?.file;
|
const file = pp.currentLexer().?.file;
|
||||||
if (file == pp.main_file) {
|
if (file == pp.main_file) {
|
||||||
_ = pp.diags.report(.{ .severity = .warning, .loc = loc, .group = "pragma-once-outside-header" }, "#pragma once in main file", .{});
|
pp.diags.warn(loc, "#pragma once in main file", .{});
|
||||||
} else {
|
} else {
|
||||||
try pp.pragma_once.put(pp.arena, try pp.fileKey(pp.sm.file(file).path), {});
|
try pp.pragma_once.put(pp.arena, try pp.fileKey(pp.sm.file(file).path), {});
|
||||||
}
|
}
|
||||||
|
|
@ -541,9 +537,7 @@ pub const Preprocessor = struct {
|
||||||
try out.append(pp.arena, t);
|
try out.append(pp.arena, t);
|
||||||
try paste.append(pp.arena, false);
|
try paste.append(pp.arena, false);
|
||||||
for (a[p]) |at| {
|
for (a[p]) |at| {
|
||||||
var c = at;
|
try out.append(pp.arena, at);
|
||||||
c.flags.from_arg = true;
|
|
||||||
try out.append(pp.arena, c);
|
|
||||||
try paste.append(pp.arena, false);
|
try paste.append(pp.arena, false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -565,7 +559,6 @@ pub const Preprocessor = struct {
|
||||||
}
|
}
|
||||||
for (toks, 0..) |at, j| {
|
for (toks, 0..) |at, j| {
|
||||||
var c = at;
|
var c = at;
|
||||||
c.flags.from_arg = true;
|
|
||||||
if (j == 0) c.flags.space = t.flags.space;
|
if (j == 0) c.flags.space = t.flags.space;
|
||||||
try out.append(pp.arena, c);
|
try out.append(pp.arena, c);
|
||||||
try paste.append(pp.arena, false);
|
try paste.append(pp.arena, false);
|
||||||
|
|
@ -651,7 +644,8 @@ pub const Preprocessor = struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn presumedLoc(pp: *const Preprocessor, loc: Loc) PresumedLoc {
|
pub fn presumedLoc(pp: *const Preprocessor, loc: Loc) PresumedLoc {
|
||||||
return pp.sm.presumedLoc(loc);
|
if (loc.isNone()) return .{ .file = "<unknown>", .line = 0 };
|
||||||
|
return pp.applyLineOverrides(loc.file, pp.sm.lineCol(loc).line);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tracks the physical line of the previous lookup so that a stream of
|
/// Tracks the physical line of the previous lookup so that a stream of
|
||||||
|
|
@ -663,16 +657,28 @@ pub const Preprocessor = struct {
|
||||||
line_index: u32 = 0,
|
line_index: u32 = 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn presumedLocCursor(pp: *const Preprocessor, loc_in: Loc, cursor: *LineCursor) PresumedLoc {
|
pub fn presumedLocCursor(pp: *const Preprocessor, loc: Loc, cursor: *LineCursor) PresumedLoc {
|
||||||
if (loc_in.isNone()) return .{ .file = "<unknown>", .line = 0 };
|
if (loc.isNone()) return .{ .file = "<unknown>", .line = 0 };
|
||||||
const loc = pp.sm.fileLoc(loc_in);
|
|
||||||
const starts = pp.sm.file(loc.file).line_starts;
|
const starts = pp.sm.file(loc.file).line_starts;
|
||||||
if (cursor.file != loc.file or starts[cursor.line_index] > loc.offset) {
|
if (cursor.file != loc.file or starts[cursor.line_index] > loc.offset) {
|
||||||
cursor.* = .{ .file = loc.file, .line_index = pp.sm.lineCol(loc).line - 1 };
|
cursor.* = .{ .file = loc.file, .line_index = pp.sm.lineCol(loc).line - 1 };
|
||||||
} else {
|
} else {
|
||||||
while (cursor.line_index + 1 < starts.len and starts[cursor.line_index + 1] <= loc.offset) cursor.line_index += 1;
|
while (cursor.line_index + 1 < starts.len and starts[cursor.line_index + 1] <= loc.offset) cursor.line_index += 1;
|
||||||
}
|
}
|
||||||
return pp.sm.presumedLine(loc.file, cursor.line_index + 1);
|
return pp.applyLineOverrides(loc.file, cursor.line_index + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn applyLineOverrides(pp: *const Preprocessor, file: source.FileId, phys: u32) PresumedLoc {
|
||||||
|
var result: PresumedLoc = .{ .file = pp.sm.file(file).path, .line = phys };
|
||||||
|
if (pp.line_overrides.count() == 0) return result;
|
||||||
|
if (pp.line_overrides.get(file)) |list| {
|
||||||
|
for (list.items) |ov| {
|
||||||
|
if (ov.phys_line >= phys) break;
|
||||||
|
result.line = ov.line + (phys - ov.phys_line - 1);
|
||||||
|
if (ov.name) |n| result.file = n;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------
|
// ---------------------------------------------------------------------
|
||||||
|
|
@ -734,7 +740,7 @@ pub const Preprocessor = struct {
|
||||||
try pp.handleInclude(name);
|
try pp.handleInclude(name);
|
||||||
} else if (std.mem.eql(u8, d, "if")) {
|
} else if (std.mem.eql(u8, d, "if")) {
|
||||||
const v = try pp.evalCondition(name);
|
const v = try pp.evalCondition(name);
|
||||||
try pp.conds.append(pp.arena, .{ .taken = v, .seen_else = false, .loc = name.loc });
|
try pp.conds.append(pp.arena, .{ .taken = v, .seen_else = false, .loc = hash.loc });
|
||||||
if (!v) try pp.skipGroup();
|
if (!v) try pp.skipGroup();
|
||||||
} else if (std.mem.eql(u8, d, "ifdef") or std.mem.eql(u8, d, "ifndef")) {
|
} else if (std.mem.eql(u8, d, "ifdef") or std.mem.eql(u8, d, "ifndef")) {
|
||||||
const toks = try pp.directiveTokens();
|
const toks = try pp.directiveTokens();
|
||||||
|
|
@ -743,7 +749,7 @@ pub const Preprocessor = struct {
|
||||||
pp.diags.err(name.loc, "macro name missing", .{});
|
pp.diags.err(name.loc, "macro name missing", .{});
|
||||||
} else v = pp.macros.contains(toks[0].text);
|
} else v = pp.macros.contains(toks[0].text);
|
||||||
if (d.len == 6) v = !v; // ifndef
|
if (d.len == 6) v = !v; // ifndef
|
||||||
try pp.conds.append(pp.arena, .{ .taken = v, .seen_else = false, .loc = name.loc });
|
try pp.conds.append(pp.arena, .{ .taken = v, .seen_else = false, .loc = hash.loc });
|
||||||
if (!v) try pp.skipGroup();
|
if (!v) try pp.skipGroup();
|
||||||
} else if (std.mem.eql(u8, d, "elif") or std.mem.eql(u8, d, "else")) {
|
} else if (std.mem.eql(u8, d, "elif") or std.mem.eql(u8, d, "else")) {
|
||||||
// Reached from an active group: the chain is done, skip the rest.
|
// Reached from an active group: the chain is done, skip the rest.
|
||||||
|
|
@ -765,9 +771,9 @@ pub const Preprocessor = struct {
|
||||||
} else if (std.mem.eql(u8, d, "pragma")) {
|
} else if (std.mem.eql(u8, d, "pragma")) {
|
||||||
return pp.handlePragma(lx.restOfLine(), hash.loc);
|
return pp.handlePragma(lx.restOfLine(), hash.loc);
|
||||||
} else if (std.mem.eql(u8, d, "error")) {
|
} else if (std.mem.eql(u8, d, "error")) {
|
||||||
pp.diags.err(name.loc, "{s}", .{lx.restOfLine()});
|
pp.diags.err(hash.loc, "{s}", .{lx.restOfLine()});
|
||||||
} else if (std.mem.eql(u8, d, "warning")) {
|
} else if (std.mem.eql(u8, d, "warning")) {
|
||||||
_ = pp.diags.report(.{ .severity = .warning, .loc = name.loc, .group = "#warnings" }, "{s}", .{lx.restOfLine()});
|
pp.diags.warn(hash.loc, "{s}", .{lx.restOfLine()});
|
||||||
} else if (std.mem.eql(u8, d, "line")) {
|
} else if (std.mem.eql(u8, d, "line")) {
|
||||||
try pp.handleLine(name);
|
try pp.handleLine(name);
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -933,12 +939,10 @@ pub const Preprocessor = struct {
|
||||||
for (body) |*t| t.flags.bol = false;
|
for (body) |*t| t.flags.bol = false;
|
||||||
m.body = body;
|
m.body = body;
|
||||||
if (pp.macros.get(name.text)) |old| {
|
if (pp.macros.get(name.text)) |old| {
|
||||||
const len: u32 = @intCast(name.text.len);
|
|
||||||
if (old.builtin != .none) {
|
if (old.builtin != .none) {
|
||||||
_ = pp.diags.report(.{ .severity = .warning, .loc = name.loc, .len = len, .group = "builtin-macro-redefined" }, "redefining builtin macro", .{});
|
pp.diags.warn(name.loc, "redefining builtin macro", .{});
|
||||||
} else if (!old.sameDefinition(m)) {
|
} else if (!old.sameDefinition(m)) {
|
||||||
const d = pp.diags.report(.{ .severity = .warning, .loc = name.loc, .len = len, .group = "macro-redefined" }, "'{s}' macro redefined", .{name.text});
|
pp.diags.warn(name.loc, "'{s}' macro redefined", .{name.text});
|
||||||
if (!old.loc.isNone()) pp.diags.note(d, old.loc, len, "previous definition is here", .{});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
try pp.defineMacro(name.text, m);
|
try pp.defineMacro(name.text, m);
|
||||||
|
|
@ -948,23 +952,13 @@ pub const Preprocessor = struct {
|
||||||
const lx = pp.currentLexer().?;
|
const lx = pp.currentLexer().?;
|
||||||
var spelled: []const u8 = undefined;
|
var spelled: []const u8 = undefined;
|
||||||
var angled = false;
|
var angled = false;
|
||||||
// Location and length of the file name, for diagnostics and the
|
|
||||||
// include chain.
|
|
||||||
var name_loc = directive.loc;
|
|
||||||
var name_len: u32 = @intCast(directive.text.len);
|
|
||||||
if (lx.headerName()) |h| {
|
if (lx.headerName()) |h| {
|
||||||
spelled = h.text[1 .. h.text.len - 1];
|
spelled = h.text[1 .. h.text.len - 1];
|
||||||
angled = true;
|
angled = true;
|
||||||
name_loc = h.loc;
|
|
||||||
name_len = @intCast(h.text.len);
|
|
||||||
pp.skipRestOfLine();
|
pp.skipRestOfLine();
|
||||||
} else {
|
} else {
|
||||||
const raw = try pp.directiveTokens();
|
const raw = try pp.directiveTokens();
|
||||||
const toks = try pp.expandIsolated(raw);
|
const toks = try pp.expandIsolated(raw);
|
||||||
if (raw.len > 0) {
|
|
||||||
name_loc = raw[0].loc;
|
|
||||||
name_len = @intCast(raw[0].text.len);
|
|
||||||
}
|
|
||||||
if (toks.len >= 1 and toks[0].kind == .string and toks[0].text.len >= 2) {
|
if (toks.len >= 1 and toks[0].kind == .string and toks[0].text.len >= 2) {
|
||||||
spelled = toks[0].text[1 .. toks[0].text.len - 1];
|
spelled = toks[0].text[1 .. toks[0].text.len - 1];
|
||||||
} else if (toks.len >= 2 and toks[0].kind == .less) {
|
} else if (toks.len >= 2 and toks[0].kind == .less) {
|
||||||
|
|
@ -987,11 +981,10 @@ pub const Preprocessor = struct {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const id = try pp.resolveInclude(spelled, angled) orelse {
|
const id = try pp.resolveInclude(spelled, angled) orelse {
|
||||||
const r: Report = .{ .severity = .fatal, .loc = name_loc, .len = name_len };
|
|
||||||
if (angled and try pp.resolveInclude(spelled, false) != null) {
|
if (angled and try pp.resolveInclude(spelled, false) != null) {
|
||||||
_ = pp.diags.report(r, "'{s}' file not found with <angled> include; use \"quotes\" instead", .{spelled});
|
pp.diags.add(.fatal, directive.loc, "'{s}' file not found with <angled> include; use \"quotes\" instead", .{spelled});
|
||||||
} else {
|
} else {
|
||||||
_ = pp.diags.report(r, "'{s}' file not found", .{spelled});
|
pp.diags.add(.fatal, directive.loc, "'{s}' file not found", .{spelled});
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
|
@ -1001,7 +994,7 @@ pub const Preprocessor = struct {
|
||||||
if (pp.macros.contains(guard)) return;
|
if (pp.macros.contains(guard)) return;
|
||||||
}
|
}
|
||||||
if (pp.pragma_once.contains(try pp.fileKey(pp.sm.file(id).path))) return;
|
if (pp.pragma_once.contains(try pp.fileKey(pp.sm.file(id).path))) return;
|
||||||
try pp.enterFileFrom(id, name_loc);
|
try pp.enterFileId(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Search order (matching dxc):
|
/// Search order (matching dxc):
|
||||||
|
|
@ -1124,7 +1117,9 @@ pub const Preprocessor = struct {
|
||||||
name = try unquoteString(pp.arena, toks[1].text);
|
name = try unquoteString(pp.arena, toks[1].text);
|
||||||
}
|
}
|
||||||
const file = pp.currentLexer().?.file;
|
const file = pp.currentLexer().?.file;
|
||||||
try pp.sm.addLineOverride(file, .{
|
const gop = try pp.line_overrides.getOrPut(pp.arena, file);
|
||||||
|
if (!gop.found_existing) gop.value_ptr.* = .empty;
|
||||||
|
try gop.value_ptr.append(pp.arena, .{
|
||||||
.phys_line = pp.sm.lineCol(directive.loc).line,
|
.phys_line = pp.sm.lineCol(directive.loc).line,
|
||||||
.line = n,
|
.line = n,
|
||||||
.name = name,
|
.name = name,
|
||||||
|
|
|
||||||
|
|
@ -6,44 +6,16 @@ const scan = @import("scan.zig");
|
||||||
|
|
||||||
pub const FileId = u32;
|
pub const FileId = u32;
|
||||||
|
|
||||||
/// A source location. Either a file location (`file` is a FileId,
|
|
||||||
/// `offset` a byte offset), or a macro location (`file` has the top bit set
|
|
||||||
/// and `offset` indexes SourceManager.expansions), as in clang.
|
|
||||||
pub const Loc = struct {
|
pub const Loc = struct {
|
||||||
file: FileId,
|
file: FileId,
|
||||||
/// Byte offset into the file's (line-spliced) text, or an expansion
|
/// Byte offset into the file's (line-spliced) text.
|
||||||
/// index for macro locations.
|
|
||||||
offset: u32,
|
offset: u32,
|
||||||
|
|
||||||
pub const none: Loc = .{ .file = std.math.maxInt(FileId), .offset = 0 };
|
pub const none: Loc = .{ .file = std.math.maxInt(FileId), .offset = 0 };
|
||||||
const macro_bit: FileId = 1 << 31;
|
|
||||||
|
|
||||||
pub fn isNone(l: Loc) bool {
|
pub fn isNone(l: Loc) bool {
|
||||||
return l.file == none.file;
|
return l.file == none.file;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn isMacro(l: Loc) bool {
|
|
||||||
return !l.isNone() and l.file & macro_bit != 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn advance(l: Loc, n: u32) Loc {
|
|
||||||
if (l.isNone() or l.isMacro()) return l;
|
|
||||||
return .{ .file = l.file, .offset = l.offset + n };
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/// One token produced by a macro expansion.
|
|
||||||
pub const Expansion = struct {
|
|
||||||
/// Where the token was spelled: in the macro definition, or for
|
|
||||||
/// argument tokens at the invocation. May itself be a macro location.
|
|
||||||
spelling: Loc,
|
|
||||||
/// Location of the macro name being expanded (may be a macro location
|
|
||||||
/// for nested expansions).
|
|
||||||
expansion: Loc,
|
|
||||||
macro_name: []const u8,
|
|
||||||
/// The token came from a macro argument: it is reported at its own
|
|
||||||
/// spelling rather than at the macro name.
|
|
||||||
is_arg: bool,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Reads files on behalf of the compiler (real filesystem, or in-memory for
|
/// Reads files on behalf of the compiler (real filesystem, or in-memory for
|
||||||
|
|
@ -116,31 +88,16 @@ pub const File = struct {
|
||||||
text: []const u8,
|
text: []const u8,
|
||||||
line_starts: []const u32,
|
line_starts: []const u32,
|
||||||
content: *Content,
|
content: *Content,
|
||||||
/// Location of the `#include` that entered this file (none for the
|
|
||||||
/// main file and pseudo-files).
|
|
||||||
included_from: Loc = .none,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const LineCol = struct { line: u32, col: u32 };
|
pub const LineCol = struct { line: u32, col: u32 };
|
||||||
|
|
||||||
/// A `#line` directive: lines after `phys_line` are renumbered from `line`.
|
|
||||||
pub const LineOverride = struct {
|
|
||||||
phys_line: u32,
|
|
||||||
line: u32,
|
|
||||||
name: ?[]const u8,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// File name and line as remapped by `#line`.
|
|
||||||
pub const PresumedLoc = struct { file: []const u8, line: u32 };
|
|
||||||
|
|
||||||
pub const SourceManager = struct {
|
pub const SourceManager = struct {
|
||||||
arena: std.heap.ArenaAllocator,
|
arena: std.heap.ArenaAllocator,
|
||||||
files: std.ArrayList(File) = .empty,
|
files: std.ArrayList(File) = .empty,
|
||||||
fs: FileSystem,
|
fs: FileSystem,
|
||||||
/// path -> contents, or null if the path could not be read.
|
/// path -> contents, or null if the path could not be read.
|
||||||
cache: std.StringHashMapUnmanaged(?*Content) = .empty,
|
cache: std.StringHashMapUnmanaged(?*Content) = .empty,
|
||||||
expansions: std.ArrayList(Expansion) = .empty,
|
|
||||||
line_overrides: std.AutoHashMapUnmanaged(FileId, std.ArrayList(LineOverride)) = .empty,
|
|
||||||
|
|
||||||
pub fn init(gpa: Allocator, fs: FileSystem) SourceManager {
|
pub fn init(gpa: Allocator, fs: FileSystem) SourceManager {
|
||||||
return .{ .arena = .init(gpa), .fs = fs };
|
return .{ .arena = .init(gpa), .fs = fs };
|
||||||
|
|
@ -188,8 +145,7 @@ pub const SourceManager = struct {
|
||||||
/// offsets refer to the spliced text.
|
/// offsets refer to the spliced text.
|
||||||
fn makeContent(sm: *SourceManager, raw: []const u8) !*Content {
|
fn makeContent(sm: *SourceManager, raw: []const u8) !*Content {
|
||||||
const a = sm.allocator();
|
const a = sm.allocator();
|
||||||
const utf8 = try decodeUtf16(a, raw) orelse raw;
|
const no_bom = if (std.mem.startsWith(u8, raw, "\xEF\xBB\xBF")) raw[3..] else raw;
|
||||||
const no_bom = if (std.mem.startsWith(u8, utf8, "\xEF\xBB\xBF")) utf8[3..] else utf8;
|
|
||||||
const text = try spliceLines(a, no_bom);
|
const text = try spliceLines(a, no_bom);
|
||||||
var starts: std.ArrayList(u32) = .empty;
|
var starts: std.ArrayList(u32) = .empty;
|
||||||
try starts.ensureTotalCapacity(a, text.len / 32 + 16);
|
try starts.ensureTotalCapacity(a, text.len / 32 + 16);
|
||||||
|
|
@ -215,69 +171,8 @@ pub const SourceManager = struct {
|
||||||
return &sm.files.items[id];
|
return &sm.files.items[id];
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn addLineOverride(sm: *SourceManager, id: FileId, ov: LineOverride) !void {
|
/// 1-based line and column.
|
||||||
const a = sm.allocator();
|
pub fn lineCol(sm: *const SourceManager, loc: Loc) LineCol {
|
||||||
const gop = try sm.line_overrides.getOrPut(a, id);
|
|
||||||
if (!gop.found_existing) gop.value_ptr.* = .empty;
|
|
||||||
try gop.value_ptr.append(a, ov);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// File name and line of `loc` after `#line` remapping.
|
|
||||||
pub fn presumedLoc(sm: *const SourceManager, loc: Loc) PresumedLoc {
|
|
||||||
if (loc.isNone()) return .{ .file = "<unknown>", .line = 0 };
|
|
||||||
const fl = sm.fileLoc(loc);
|
|
||||||
return sm.presumedLine(fl.file, sm.lineCol(fl).line);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn presumedLine(sm: *const SourceManager, id: FileId, phys: u32) PresumedLoc {
|
|
||||||
var result: PresumedLoc = .{ .file = sm.file(id).path, .line = phys };
|
|
||||||
if (sm.line_overrides.count() == 0) return result;
|
|
||||||
if (sm.line_overrides.get(id)) |list| {
|
|
||||||
for (list.items) |ov| {
|
|
||||||
if (ov.phys_line >= phys) break;
|
|
||||||
result.line = ov.line + (phys - ov.phys_line - 1);
|
|
||||||
if (ov.name) |n| result.file = n;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn setIncludedFrom(sm: *SourceManager, id: FileId, loc: Loc) void {
|
|
||||||
sm.files.items[id].included_from = loc;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Record a macro-expanded token and return its macro location.
|
|
||||||
pub fn addExpansion(sm: *SourceManager, e: Expansion) !Loc {
|
|
||||||
try sm.expansions.append(sm.allocator(), e);
|
|
||||||
return .{ .file = Loc.macro_bit, .offset = @intCast(sm.expansions.items.len - 1) };
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn expansion(sm: *const SourceManager, loc: Loc) *const Expansion {
|
|
||||||
std.debug.assert(loc.isMacro());
|
|
||||||
return &sm.expansions.items[loc.offset];
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The file location a (possibly macro) location is reported at: the
|
|
||||||
/// outermost expansion point, or for argument tokens their own position.
|
|
||||||
pub fn fileLoc(sm: *const SourceManager, loc: Loc) Loc {
|
|
||||||
var l = loc;
|
|
||||||
while (l.isMacro()) {
|
|
||||||
const e = sm.expansion(l);
|
|
||||||
l = if (e.is_arg) e.spelling else e.expansion;
|
|
||||||
}
|
|
||||||
return l;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where the token was actually written.
|
|
||||||
pub fn spellingLoc(sm: *const SourceManager, loc: Loc) Loc {
|
|
||||||
var l = loc;
|
|
||||||
while (l.isMacro()) l = sm.expansion(l).spelling;
|
|
||||||
return l;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 1-based line and column (macro locations are resolved to fileLoc).
|
|
||||||
pub fn lineCol(sm: *const SourceManager, loc_in: Loc) LineCol {
|
|
||||||
const loc = sm.fileLoc(loc_in);
|
|
||||||
const f = sm.file(loc.file);
|
const f = sm.file(loc.file);
|
||||||
const idx = std.sort.upperBound(u32, f.line_starts, loc.offset, struct {
|
const idx = std.sort.upperBound(u32, f.line_starts, loc.offset, struct {
|
||||||
fn cmp(target: u32, x: u32) std.math.Order {
|
fn cmp(target: u32, x: u32) std.math.Order {
|
||||||
|
|
@ -289,8 +184,7 @@ pub const SourceManager = struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Text of the line containing `loc`, without the newline.
|
/// Text of the line containing `loc`, without the newline.
|
||||||
pub fn lineText(sm: *const SourceManager, loc_in: Loc) []const u8 {
|
pub fn lineText(sm: *const SourceManager, loc: Loc) []const u8 {
|
||||||
const loc = sm.fileLoc(loc_in);
|
|
||||||
const f = sm.file(loc.file);
|
const f = sm.file(loc.file);
|
||||||
const lc = sm.lineCol(loc);
|
const lc = sm.lineCol(loc);
|
||||||
const start = f.line_starts[lc.line - 1];
|
const start = f.line_starts[lc.line - 1];
|
||||||
|
|
@ -300,22 +194,6 @@ pub const SourceManager = struct {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/// UTF-16 text with a byte-order mark is converted to UTF-8 (as dxc does);
|
|
||||||
/// returns null for anything else.
|
|
||||||
fn decodeUtf16(a: Allocator, raw: []const u8) !?[]const u8 {
|
|
||||||
if (raw.len < 2) return null;
|
|
||||||
const little = raw[0] == 0xFF and raw[1] == 0xFE;
|
|
||||||
const big = raw[0] == 0xFE and raw[1] == 0xFF;
|
|
||||||
if (!little and !big) return null;
|
|
||||||
const units = try a.alloc(u16, (raw.len - 2) / 2);
|
|
||||||
for (units, 0..) |*u, i| {
|
|
||||||
const b = raw[2 + 2 * i ..][0..2];
|
|
||||||
u.* = if (little) std.mem.readInt(u16, b, .little) else std.mem.readInt(u16, b, .big);
|
|
||||||
}
|
|
||||||
// Lone surrogates make the text invalid; fall back to the raw bytes.
|
|
||||||
return std.unicode.utf16LeToUtf8Alloc(a, units) catch null;
|
|
||||||
}
|
|
||||||
|
|
||||||
fn spliceLines(a: Allocator, raw: []const u8) ![]const u8 {
|
fn spliceLines(a: Allocator, raw: []const u8) ![]const u8 {
|
||||||
if (std.mem.indexOfScalar(u8, raw, '\\') == null) return raw;
|
if (std.mem.indexOfScalar(u8, raw, '\\') == null) return raw;
|
||||||
var out: std.ArrayList(u8) = .empty;
|
var out: std.ArrayList(u8) = .empty;
|
||||||
|
|
@ -366,16 +244,6 @@ test "files are read once per path" {
|
||||||
try std.testing.expect(try sm.load("missing.h") == null);
|
try std.testing.expect(try sm.load("missing.h") == null);
|
||||||
}
|
}
|
||||||
|
|
||||||
test "UTF-16 sources are decoded" {
|
|
||||||
var mfs: MemoryFs = .{};
|
|
||||||
var sm = SourceManager.init(std.testing.allocator, mfs.fileSystem());
|
|
||||||
defer sm.deinit();
|
|
||||||
const id = try sm.addFile("le.hlsl", "\xFF\xFEi\x00n\x00t\x00");
|
|
||||||
try std.testing.expectEqualStrings("int", sm.file(id).text);
|
|
||||||
const id2 = try sm.addFile("be.hlsl", "\xFE\xFF\x00x");
|
|
||||||
try std.testing.expectEqualStrings("x", sm.file(id2).text);
|
|
||||||
}
|
|
||||||
|
|
||||||
test "line splicing" {
|
test "line splicing" {
|
||||||
var mfs: MemoryFs = .{};
|
var mfs: MemoryFs = .{};
|
||||||
var sm = SourceManager.init(std.testing.allocator, mfs.fileSystem());
|
var sm = SourceManager.init(std.testing.allocator, mfs.fileSystem());
|
||||||
|
|
|
||||||
213
src/main.zig
213
src/main.zig
|
|
@ -5,7 +5,31 @@ const shader = zdxc.dxil.shader;
|
||||||
const container = zdxc.dxil.container;
|
const container = zdxc.dxil.container;
|
||||||
const front = zdxc.front;
|
const front = zdxc.front;
|
||||||
|
|
||||||
const options = zdxc.options;
|
const usage =
|
||||||
|
\\OVERVIEW: zdxc - HLSL 2021 to DXIL / SPIR-V compiler
|
||||||
|
\\
|
||||||
|
\\USAGE: zdxc [options] <input>
|
||||||
|
\\
|
||||||
|
\\OPTIONS:
|
||||||
|
\\ -T <profile> Target profile (cs_6_0 .. cs_6_9, vs_, ps_, gs_)
|
||||||
|
\\ -E <name> Entry point name (default: main)
|
||||||
|
\\ -Fo <file> Output object file
|
||||||
|
\\ -spirv Generate SPIR-V
|
||||||
|
\\ -D <name>[=<value>] Define a macro
|
||||||
|
\\ -I <dir> Add an include directory
|
||||||
|
\\ -P Preprocess only (to -Fi <file>, or stdout)
|
||||||
|
\\ -Fi <file> Output file for -P
|
||||||
|
\\ -HV 2021 HLSL version (only 2021 is supported)
|
||||||
|
\\ -enable-16bit-types Enable 16-bit types
|
||||||
|
\\ --version Print version
|
||||||
|
\\
|
||||||
|
\\DEVELOPMENT (temporary, until the frontend lands):
|
||||||
|
\\ -zdxc-empty Emit an empty shader for -T instead of compiling <input>
|
||||||
|
\\ -zdxc-check-hash Verify the container hash of <input>
|
||||||
|
\\ -zdxc-lex Print the tokens of <input>, one per line (no preprocessing;
|
||||||
|
\\ `#line` lines are skipped)
|
||||||
|
\\
|
||||||
|
;
|
||||||
|
|
||||||
const Options = struct {
|
const Options = struct {
|
||||||
profile: ?[]const u8 = null,
|
profile: ?[]const u8 = null,
|
||||||
|
|
@ -21,18 +45,6 @@ const Options = struct {
|
||||||
empty: bool = false,
|
empty: bool = false,
|
||||||
check_hash: bool = false,
|
check_hash: bool = false,
|
||||||
lex: bool = false,
|
lex: bool = false,
|
||||||
warnings_as_errors: bool = false,
|
|
||||||
no_warnings: bool = false,
|
|
||||||
disabled_warnings: std.ArrayList([]const u8) = .empty,
|
|
||||||
diag_format: zdxc.diag.Format = .clang,
|
|
||||||
color: ?bool = null,
|
|
||||||
error_limit: u32 = 20,
|
|
||||||
parse: bool = false,
|
|
||||||
dump_ast: 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.
|
|
||||||
ignored: std.ArrayList([]const u8) = .empty,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const Cli = struct {
|
const Cli = struct {
|
||||||
|
|
@ -54,122 +66,72 @@ pub fn main(init: std.process.Init) !u8 {
|
||||||
var stdout_buf: [4096]u8 = undefined;
|
var stdout_buf: [4096]u8 = undefined;
|
||||||
var stdout_writer: Io.File.Writer = .init(.stdout(), io, &stdout_buf);
|
var stdout_writer: Io.File.Writer = .init(.stdout(), io, &stdout_buf);
|
||||||
const cli: Cli = .{ .io = io, .stderr = &stderr_writer.interface };
|
const cli: Cli = .{ .io = io, .stderr = &stderr_writer.interface };
|
||||||
defer stderr_writer.interface.flush() catch {};
|
|
||||||
|
|
||||||
// Exit codes follow dxc: 1 for command-line and I/O errors, 5 when the
|
|
||||||
// compilation reports errors.
|
|
||||||
run(cli, arena, try init.minimal.args.toSlice(arena), &stdout_writer.interface) catch |err| switch (err) {
|
run(cli, arena, try init.minimal.args.toSlice(arena), &stdout_writer.interface) catch |err| switch (err) {
|
||||||
error.Fatal => return 1,
|
error.Fatal => return 1,
|
||||||
error.CompileFailed => return 5,
|
|
||||||
else => return err,
|
else => return err,
|
||||||
};
|
};
|
||||||
try stdout_writer.interface.flush();
|
try stdout_writer.interface.flush();
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parse a dxc-style command line. Returns null when the command is
|
/// Splits `-Dfoo` / `-D foo` style options.
|
||||||
/// complete (`-help`, `--version`).
|
fn optionValue(cli: Cli, args: []const [:0]const u8, i: *usize, flag: []const u8) ![]const u8 {
|
||||||
fn parseArgs(cli: Cli, arena: std.mem.Allocator, argv: []const [:0]const u8, stdout: *Io.Writer) !?Options {
|
const a = args[i.*];
|
||||||
var failure: options.Failure = .{};
|
if (a.len > flag.len) return a[flag.len..];
|
||||||
const plain = try arena.alloc([]const u8, argv.len -| 1);
|
i.* += 1;
|
||||||
for (plain, 0..) |*a, i| a.* = argv[i + 1];
|
if (i.* >= args.len) return cli.fail("missing argument to '{s}'", .{flag});
|
||||||
const parsed = options.parse(arena, plain, &failure) catch |e| switch (e) {
|
return args[i.*];
|
||||||
error.UnknownArgument => return cli.fail("unknown argument: '{s}'", .{failure.arg}),
|
}
|
||||||
error.MissingArgument => return cli.fail("argument to '{s}' is missing", .{failure.arg}),
|
|
||||||
error.OutOfMemory => return error.OutOfMemory,
|
|
||||||
};
|
|
||||||
|
|
||||||
|
fn parseArgs(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *Io.Writer) !?Options {
|
||||||
var opts: Options = .{};
|
var opts: Options = .{};
|
||||||
for (parsed.args) |a| {
|
var i: usize = 1;
|
||||||
switch (a.which) {
|
while (i < args.len) : (i += 1) {
|
||||||
.extra => |x| switch (x) {
|
const a = args[i];
|
||||||
.zdxc_empty => opts.empty = true,
|
if (std.mem.eql(u8, a, "-T")) {
|
||||||
.zdxc_check_hash => opts.check_hash = true,
|
opts.profile = try optionValue(cli, args, &i, "-T");
|
||||||
.zdxc_lex => opts.lex = true,
|
} else if (std.mem.eql(u8, a, "-E")) {
|
||||||
.zdxc_parse => opts.parse = true,
|
opts.entry = try optionValue(cli, args, &i, "-E");
|
||||||
.zdxc_ast => {
|
} else if (std.mem.eql(u8, a, "-Fo")) {
|
||||||
opts.parse = true;
|
opts.output = try optionValue(cli, args, &i, "-Fo");
|
||||||
opts.dump_ast = true;
|
} else if (std.mem.eql(u8, a, "-Fi")) {
|
||||||
},
|
opts.pp_output = try optionValue(cli, args, &i, "-Fi");
|
||||||
.fcolor_diagnostics => opts.color = true,
|
} else if (std.mem.startsWith(u8, a, "-D")) {
|
||||||
.fno_color_diagnostics => opts.color = false,
|
const v = try optionValue(cli, args, &i, "-D");
|
||||||
},
|
if (std.mem.indexOfScalar(u8, v, '=')) |eq| {
|
||||||
.dxc => |id| {
|
try opts.defines.append(arena, .{ .name = v[0..eq], .value = v[eq + 1 ..] });
|
||||||
switch (options.support(id)) {
|
} else try opts.defines.append(arena, .{ .name = v });
|
||||||
.implemented => {},
|
} else if (std.mem.startsWith(u8, a, "-I")) {
|
||||||
.ignored => {
|
try opts.include_dirs.append(arena, try optionValue(cli, args, &i, "-I"));
|
||||||
try opts.ignored.append(arena, a.spelling);
|
} else if (std.mem.eql(u8, a, "-HV")) {
|
||||||
continue;
|
const v = try optionValue(cli, args, &i, "-HV");
|
||||||
},
|
if (!std.mem.eql(u8, v, "2021")) return cli.fail("HLSL version {s} is not supported; zdxc implements HLSL 2021 only", .{v});
|
||||||
.unsupported => |why| return cli.fail("'{s}' is not supported: {s}", .{ a.spelling, why }),
|
} else if (std.mem.eql(u8, a, "-P")) {
|
||||||
}
|
opts.preprocess = true;
|
||||||
const v = a.value();
|
} else if (std.mem.eql(u8, a, "-spirv")) {
|
||||||
switch (id) {
|
opts.spirv = true;
|
||||||
.target_profile => opts.profile = v,
|
} else if (std.mem.eql(u8, a, "-enable-16bit-types")) {
|
||||||
.entrypoint => opts.entry = v,
|
opts.enable_16bit = true;
|
||||||
.Fo => opts.output = v,
|
} else if (std.mem.eql(u8, a, "-zdxc-empty")) {
|
||||||
.Fi => opts.pp_output = v,
|
opts.empty = true;
|
||||||
.D => if (std.mem.indexOfScalar(u8, v, '=')) |eq| {
|
} else if (std.mem.eql(u8, a, "-zdxc-check-hash")) {
|
||||||
try opts.defines.append(arena, .{ .name = v[0..eq], .value = v[eq + 1 ..] });
|
opts.check_hash = true;
|
||||||
} else try opts.defines.append(arena, .{ .name = v }),
|
} else if (std.mem.eql(u8, a, "-zdxc-lex")) {
|
||||||
.I => try opts.include_dirs.append(arena, v),
|
opts.lex = true;
|
||||||
.hlsl_version => if (!std.mem.eql(u8, v, "2021")) {
|
} else if (std.mem.eql(u8, a, "--version")) {
|
||||||
return cli.fail("HLSL version {s} is not supported; zdxc implements HLSL 2021 only", .{v});
|
try stdout.print("zdxc {s}\n", .{zdxc.version});
|
||||||
},
|
return null;
|
||||||
.P => opts.preprocess = true,
|
} else if (std.mem.eql(u8, a, "-help") or std.mem.eql(u8, a, "--help")) {
|
||||||
.spirv => opts.spirv = true,
|
try stdout.writeAll(usage);
|
||||||
.enable_16bit_types => opts.enable_16bit = true,
|
return null;
|
||||||
._SLASH_WX => opts.warnings_as_errors = true,
|
} else if (a.len > 0 and a[0] == '-') {
|
||||||
.no_warnings => opts.no_warnings = true,
|
return cli.fail("unknown argument: '{s}'", .{a});
|
||||||
.W_Joined => {
|
} else {
|
||||||
// -Wno-<group>, -Werror; enabling groups is a no-op.
|
if (opts.input != null) return cli.fail("more than one input file", .{});
|
||||||
if (std.mem.startsWith(u8, v, "no-")) {
|
opts.input = a;
|
||||||
try opts.disabled_warnings.append(arena, v[3..]);
|
|
||||||
} else if (std.mem.eql(u8, v, "error")) opts.warnings_as_errors = true;
|
|
||||||
},
|
|
||||||
.Wno_vk_ignored_features => try opts.disabled_warnings.append(arena, "vk-ignored-features"),
|
|
||||||
.Wno_vk_emulated_features => try opts.disabled_warnings.append(arena, "vk-emulated-features"),
|
|
||||||
.fdiagnostics_format_EQ => {
|
|
||||||
// dxc also accepts msvc-fallback.
|
|
||||||
const name = if (std.mem.eql(u8, v, "msvc-fallback")) "msvc" else v;
|
|
||||||
opts.diag_format = std.meta.stringToEnum(zdxc.diag.Format, name) orelse
|
|
||||||
return cli.fail("unknown diagnostics format '{s}' (expected clang, msvc or vi)", .{v});
|
|
||||||
},
|
|
||||||
.ferror_limit_EQ => opts.error_limit = std.fmt.parseInt(u32, v, 10) catch
|
|
||||||
return cli.fail("invalid -ferror-limit value '{s}'", .{v}),
|
|
||||||
.fdiagnostics_color => opts.color = true,
|
|
||||||
.fdiagnostics_color_EQ => opts.color = if (std.mem.eql(u8, v, "always"))
|
|
||||||
true
|
|
||||||
else if (std.mem.eql(u8, v, "never"))
|
|
||||||
false
|
|
||||||
else
|
|
||||||
null,
|
|
||||||
.help, ._help_question, ._help_hidden => {
|
|
||||||
try options.printHelp(stdout, id == ._help_hidden);
|
|
||||||
return null;
|
|
||||||
},
|
|
||||||
._version => {
|
|
||||||
try stdout.print("zdxc {s} (dxc-compatible command line, HLSL 2021)\n", .{zdxc.version});
|
|
||||||
return null;
|
|
||||||
},
|
|
||||||
.O0 => opts.opt_level = .o0,
|
|
||||||
.O1 => opts.opt_level = .o1,
|
|
||||||
.O2 => opts.opt_level = .o2,
|
|
||||||
.O3 => opts.opt_level = .o3,
|
|
||||||
.Od => opts.opt_level = .od,
|
|
||||||
else => {}, // implemented as a no-op (e.g. -Vd, -nologo)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Like dxc, the last input wins (dxc reads getLastArgValue(OPT_INPUT)).
|
|
||||||
if (parsed.inputs.len > 0) opts.input = parsed.inputs[parsed.inputs.len - 1];
|
|
||||||
|
|
||||||
if (opts.ignored.items.len > 0 and !opts.no_warnings) {
|
|
||||||
try cli.stderr.writeAll("zdxc: note: accepted for compatibility, no effect yet:");
|
|
||||||
for (opts.ignored.items) |sp| try cli.stderr.print(" {s}", .{sp});
|
|
||||||
try cli.stderr.writeByte('\n');
|
|
||||||
}
|
|
||||||
return opts;
|
return opts;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -211,15 +173,11 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
|
||||||
else
|
else
|
||||||
null;
|
null;
|
||||||
|
|
||||||
if (opts.preprocess or opts.parse) {
|
if (opts.preprocess) {
|
||||||
const input = opts.input orelse return cli.fail("no input file", .{});
|
const input = opts.input orelse return cli.fail("no input file", .{});
|
||||||
var disk: front.source.DiskFs = .{ .io = cli.io };
|
var disk: front.source.DiskFs = .{ .io = cli.io };
|
||||||
var sm = front.source.SourceManager.init(arena, disk.fileSystem());
|
var sm = front.source.SourceManager.init(arena, disk.fileSystem());
|
||||||
var diags = zdxc.Diagnostics.init(arena);
|
var diags = zdxc.Diagnostics.init(arena);
|
||||||
diags.warnings_as_errors = opts.warnings_as_errors;
|
|
||||||
diags.suppress_warnings = opts.no_warnings;
|
|
||||||
diags.error_limit = opts.error_limit;
|
|
||||||
for (opts.disabled_warnings.items) |g| try diags.disableGroup(g);
|
|
||||||
var pp = front.preproc.Preprocessor.init(arena, &sm, &diags, .{
|
var pp = front.preproc.Preprocessor.init(arena, &sm, &diags, .{
|
||||||
.defines = opts.defines.items,
|
.defines = opts.defines.items,
|
||||||
.include_dirs = opts.include_dirs.items,
|
.include_dirs = opts.include_dirs.items,
|
||||||
|
|
@ -230,17 +188,10 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
|
||||||
.enable_16bit = opts.enable_16bit,
|
.enable_16bit = opts.enable_16bit,
|
||||||
});
|
});
|
||||||
var out: Io.Writer.Allocating = .init(arena);
|
var out: Io.Writer.Allocating = .init(arena);
|
||||||
if (try pp.enterMainFile(input)) {
|
if (try pp.enterMainFile(input)) try front.pp_print.print(&pp, &out.writer);
|
||||||
if (opts.parse) {
|
try diags.render(&sm, cli.stderr);
|
||||||
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);
|
|
||||||
}
|
|
||||||
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();
|
try cli.stderr.flush();
|
||||||
if (diags.hasErrors()) return error.CompileFailed;
|
if (diags.hasErrors()) return error.Fatal;
|
||||||
if (opts.pp_output) |path| {
|
if (opts.pp_output) |path| {
|
||||||
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = path, .data = out.written() });
|
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = path, .data = out.written() });
|
||||||
} else try stdout.writeAll(out.written());
|
} else try stdout.writeAll(out.written());
|
||||||
|
|
|
||||||
344
src/options.zig
344
src/options.zig
|
|
@ -1,344 +0,0 @@
|
||||||
//! dxc-compatible command-line parsing.
|
|
||||||
//!
|
|
||||||
//! The option table is generated from dxc's own definitions
|
|
||||||
//! (vendor/dxc/HLSLOptions.td) and matched with the same rules as LLVM's
|
|
||||||
//! OptTable, which dxc uses: `-`, `/` and `--` prefixes, longest spelling
|
|
||||||
//! first, flags must match exactly, joined / separate / joined-or-separate
|
|
||||||
//! values, and `/`-prefixed arguments that match nothing are input paths.
|
|
||||||
//! A few zdxc-only options (`-zdxc-*`, color control) are added on top under
|
|
||||||
//! names dxc does not use.
|
|
||||||
//!
|
|
||||||
//! Every dxc option has a support level: implemented, accepted with no
|
|
||||||
//! effect yet, or unsupported (with a reason), so that a dxc command line
|
|
||||||
//! either works or fails with a clear message.
|
|
||||||
|
|
||||||
const std = @import("std");
|
|
||||||
const Allocator = std.mem.Allocator;
|
|
||||||
const table = @import("options_table");
|
|
||||||
|
|
||||||
pub const Id = table.Id;
|
|
||||||
pub const Kind = table.Kind;
|
|
||||||
pub const Option = table.Option;
|
|
||||||
|
|
||||||
/// zdxc-only options. They use the same matching rules.
|
|
||||||
pub const Extra = enum {
|
|
||||||
zdxc_empty,
|
|
||||||
zdxc_check_hash,
|
|
||||||
zdxc_lex,
|
|
||||||
zdxc_parse,
|
|
||||||
zdxc_ast,
|
|
||||||
fcolor_diagnostics,
|
|
||||||
fno_color_diagnostics,
|
|
||||||
};
|
|
||||||
|
|
||||||
const extra_options = [_]struct { id: Extra, spelling: []const u8, help: []const u8 }{
|
|
||||||
.{ .id = .zdxc_empty, .spelling = "zdxc-empty", .help = "Emit an empty shader for -T instead of compiling the input (development)" },
|
|
||||||
.{ .id = .zdxc_check_hash, .spelling = "zdxc-check-hash", .help = "Verify the container hash of the input (development)" },
|
|
||||||
.{ .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 = .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" },
|
|
||||||
};
|
|
||||||
|
|
||||||
pub const Arg = struct {
|
|
||||||
which: union(enum) { dxc: Id, extra: Extra },
|
|
||||||
/// The argument as written, for messages (`-T`, `/Fo`).
|
|
||||||
spelling: []const u8,
|
|
||||||
values: []const []const u8,
|
|
||||||
|
|
||||||
pub fn is(a: Arg, id: Id) bool {
|
|
||||||
return a.which == .dxc and a.which.dxc == id;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn value(a: Arg) []const u8 {
|
|
||||||
return if (a.values.len > 0) a.values[0] else "";
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
pub const Parsed = struct {
|
|
||||||
args: []const Arg,
|
|
||||||
inputs: []const []const u8,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub const ParseError = error{ UnknownArgument, MissingArgument } || Allocator.Error;
|
|
||||||
|
|
||||||
/// Details of the last ParseError, for the error message.
|
|
||||||
pub const Failure = struct { arg: []const u8 = "" };
|
|
||||||
|
|
||||||
/// Parse `argv` (without the program name).
|
|
||||||
pub fn parse(arena: Allocator, argv: []const []const u8, failure: *Failure) ParseError!Parsed {
|
|
||||||
var args: std.ArrayList(Arg) = .empty;
|
|
||||||
var inputs: std.ArrayList([]const u8) = .empty;
|
|
||||||
var i: usize = 0;
|
|
||||||
while (i < argv.len) {
|
|
||||||
const str = argv[i];
|
|
||||||
if (!isOptionLike(str)) {
|
|
||||||
try inputs.append(arena, str);
|
|
||||||
i += 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const r = try parseOne(arena, argv, &i, failure);
|
|
||||||
if (r) |a| {
|
|
||||||
try args.append(arena, a);
|
|
||||||
} else if (str[0] == '/') {
|
|
||||||
// Not an option: a path such as /Users/me/shader.hlsl.
|
|
||||||
try inputs.append(arena, str);
|
|
||||||
i += 1;
|
|
||||||
} else {
|
|
||||||
failure.arg = str;
|
|
||||||
return error.UnknownArgument;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return .{ .args = args.items, .inputs = inputs.items };
|
|
||||||
}
|
|
||||||
|
|
||||||
fn isOptionLike(s: []const u8) bool {
|
|
||||||
if (s.len < 2) return false; // "-" alone is an input (stdin)
|
|
||||||
return s[0] == '-' or s[0] == '/';
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Candidate match: an option (dxc or extra) whose prefix + spelling
|
|
||||||
/// starts `str`.
|
|
||||||
const Candidate = struct {
|
|
||||||
which: @FieldType(Arg, "which"),
|
|
||||||
kind: Kind,
|
|
||||||
count: u8,
|
|
||||||
prefix_len: usize,
|
|
||||||
spelling_len: usize,
|
|
||||||
};
|
|
||||||
|
|
||||||
fn prefixFits(str: []const u8, pre: []const u8, spelling: []const u8) bool {
|
|
||||||
return std.mem.startsWith(u8, str, pre) and std.mem.startsWith(u8, str[pre.len..], spelling);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parseOne(arena: Allocator, argv: []const []const u8, index: *usize, failure: *Failure) ParseError!?Arg {
|
|
||||||
const str = argv[index.*];
|
|
||||||
var cands: [16]Candidate = undefined;
|
|
||||||
var n: usize = 0;
|
|
||||||
for (table.options) |o| {
|
|
||||||
const prefixes = [_]struct { bool, []const u8 }{ .{ o.dash_dash, "--" }, .{ o.dash, "-" }, .{ o.slash, "/" } };
|
|
||||||
for (prefixes) |pp| {
|
|
||||||
if (!pp[0] or !prefixFits(str, pp[1], o.spelling)) continue;
|
|
||||||
if (n < cands.len) {
|
|
||||||
cands[n] = .{ .which = .{ .dxc = o.alias orelse o.id }, .kind = o.kind, .count = o.count, .prefix_len = pp[1].len, .spelling_len = o.spelling.len };
|
|
||||||
n += 1;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (extra_options) |o| {
|
|
||||||
if (prefixFits(str, "-", o.spelling) and n < cands.len) {
|
|
||||||
cands[n] = .{ .which = .{ .extra = o.id }, .kind = .flag, .count = 0, .prefix_len = 1, .spelling_len = o.spelling.len };
|
|
||||||
n += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Longest spelling first, as OptTable's sorted search does.
|
|
||||||
std.mem.sort(Candidate, cands[0..n], {}, struct {
|
|
||||||
fn gt(_: void, a: Candidate, b: Candidate) bool {
|
|
||||||
return a.spelling_len > b.spelling_len;
|
|
||||||
}
|
|
||||||
}.gt);
|
|
||||||
|
|
||||||
for (cands[0..n]) |c| {
|
|
||||||
const name_end = c.prefix_len + c.spelling_len;
|
|
||||||
const rest = str[name_end..];
|
|
||||||
const spelling = str[0..name_end];
|
|
||||||
switch (c.kind) {
|
|
||||||
.flag => {
|
|
||||||
if (rest.len != 0) continue;
|
|
||||||
index.* += 1;
|
|
||||||
return .{ .which = c.which, .spelling = spelling, .values = &.{} };
|
|
||||||
},
|
|
||||||
.joined => {
|
|
||||||
index.* += 1;
|
|
||||||
return .{ .which = c.which, .spelling = spelling, .values = try dupeOne(arena, rest) };
|
|
||||||
},
|
|
||||||
.comma_joined => {
|
|
||||||
index.* += 1;
|
|
||||||
var vals: std.ArrayList([]const u8) = .empty;
|
|
||||||
var it = std.mem.splitScalar(u8, rest, ',');
|
|
||||||
while (it.next()) |v| try vals.append(arena, v);
|
|
||||||
return .{ .which = c.which, .spelling = spelling, .values = vals.items };
|
|
||||||
},
|
|
||||||
.separate, .joined_or_separate => {
|
|
||||||
if (rest.len != 0) {
|
|
||||||
if (c.kind == .separate) continue;
|
|
||||||
index.* += 1;
|
|
||||||
return .{ .which = c.which, .spelling = spelling, .values = try dupeOne(arena, rest) };
|
|
||||||
}
|
|
||||||
if (index.* + 1 >= argv.len) {
|
|
||||||
failure.arg = spelling;
|
|
||||||
return error.MissingArgument;
|
|
||||||
}
|
|
||||||
index.* += 2;
|
|
||||||
return .{ .which = c.which, .spelling = spelling, .values = try dupeOne(arena, argv[index.* - 1]) };
|
|
||||||
},
|
|
||||||
.multi_arg => {
|
|
||||||
if (rest.len != 0) continue;
|
|
||||||
if (index.* + c.count >= argv.len) {
|
|
||||||
failure.arg = spelling;
|
|
||||||
return error.MissingArgument;
|
|
||||||
}
|
|
||||||
const vals = try arena.dupe([]const u8, argv[index.* + 1 ..][0..c.count]);
|
|
||||||
index.* += 1 + c.count;
|
|
||||||
return .{ .which = c.which, .spelling = spelling, .values = vals };
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
fn dupeOne(arena: Allocator, v: []const u8) Allocator.Error![]const []const u8 {
|
|
||||||
const vals = try arena.alloc([]const u8, 1);
|
|
||||||
vals[0] = v;
|
|
||||||
return vals;
|
|
||||||
}
|
|
||||||
|
|
||||||
// -------------------------------------------------------------------------
|
|
||||||
// Support levels
|
|
||||||
|
|
||||||
pub const Support = union(enum) {
|
|
||||||
implemented,
|
|
||||||
/// Accepted for compatibility; has no effect (yet).
|
|
||||||
ignored,
|
|
||||||
/// Rejected with this reason.
|
|
||||||
unsupported: []const u8,
|
|
||||||
};
|
|
||||||
|
|
||||||
const dropped_debug = "debug information and PDBs are not supported by zdxc";
|
|
||||||
const dropped_disasm = "disassembly is not part of zdxc; use dxc -dumpbin to inspect output";
|
|
||||||
const dropped_tooling = "this dxc tooling option is not part of zdxc";
|
|
||||||
const dropped_internal = "dxc-internal (LLVM pass / codegen debugging) options are not supported";
|
|
||||||
const not_yet = "not supported by zdxc yet";
|
|
||||||
|
|
||||||
/// The support level of each dxc option. Options not listed are
|
|
||||||
/// unsupported ("not supported by zdxc yet").
|
|
||||||
pub fn support(id: Id) Support {
|
|
||||||
return switch (id) {
|
|
||||||
// Core compilation.
|
|
||||||
.target_profile, .entrypoint, .Fo, .D, .I, .P, .Fi, .hlsl_version, .spirv, .enable_16bit_types => .implemented,
|
|
||||||
// Diagnostics.
|
|
||||||
._SLASH_WX, .no_warnings, .W_Joined, .Wno_vk_ignored_features, .Wno_vk_emulated_features => .implemented,
|
|
||||||
.fdiagnostics_format_EQ, .ferror_limit_EQ, .fdiagnostics_color, .fdiagnostics_color_EQ => .implemented,
|
|
||||||
// Information.
|
|
||||||
.help, ._help_question, ._help_hidden, ._version, .nologo => .implemented,
|
|
||||||
// Optimization levels: recorded; zdxc's optimizer is simpler.
|
|
||||||
.O0, .O1, .O2, .O3, .Od => .implemented,
|
|
||||||
// zdxc signs its own output and has no separate validation step.
|
|
||||||
.VD, .validator_version => .implemented,
|
|
||||||
|
|
||||||
// Accepted for build-script compatibility; no effect yet.
|
|
||||||
.Zpr, .Zpc, .Gis, .Gfa, .Gfp, .Ges, .Gec, .denorm, .all_resources_bound, .all_resources_bound_, .res_may_alias, .res_may_alias_, .pack_optimized, .pack_optimized_, .pack_prefix_stable, .pack_prefix_stable_, .ffinite_math_only, .fno_finite_math_only, .flegacy_macro_expansion, .flegacy_resource_reservation, .no_legacy_cbuf_layout, .not_use_legacy_cbuf_load_, .enable_payload_qualifiers, .disable_payload_qualifiers, .enable_lifetime_markers, .disable_lifetime_markers, .force_zero_store_lifetimes, .ignore_line_directives, .Qunused_arguments, .fdiagnostics_show_option, .fno_diagnostics_show_option, .fdiagnostics_show_category_EQ, ._vi, .verbose, .v, .encoding, .Wall, .Wdeprecated, ._all_warnings, .Fh, .Vn, .Fsh, .Frs, .Fre, .Zss, .Zsb, .Qstrip_reflect, .Qstrip_debug, .Qstrip_priv, .Qstrip_rootsignature, .Qkeep_reflect_in_dxil, .Qstrip_reflect_from_dxil, .force_rootsig_ver, .force_rootsig_ver_, .rootsig_define, .auto_binding_space, .exports, .export_shaders_only, .default_linkage, .fvk_stage_io_order_EQ, .fvk_b_shift, .fvk_t_shift, .fvk_s_shift, .fvk_u_shift, .fvk_bind_globals, .fvk_bind_register, .vkbr, .fvk_invert_y, .fvk_use_dx_position_w, .fvk_support_nonzero_base_instance, .fvk_support_nonzero_base_vertex, .fvk_use_gl_layout, .fvk_use_dx_layout, .fvk_use_scalar_layout, .fspv_use_legacy_buffer_matrix_order, .fspv_reflect, .fspv_extension_EQ, .fspv_target_env_EQ, .fspv_flatten_resource_arrays, .fspv_reduce_load_size, .fspv_fix_func_call_arguments, .fspv_entrypoint_name_EQ, .fspv_enable_maximal_reconvergence, .fspv_use_vulkan_memory_model, .fspv_use_unknown_image_format, .fvk_auto_shift_bindings, .fspv_preserve_bindings, .fspv_preserve_interface, .Oconfig => .ignored,
|
|
||||||
|
|
||||||
// Dropped by design (see the zdxc plan).
|
|
||||||
._SLASH_Zi, .Zs, .Fd, .Qembed_debug, .Qsource_in_debug_module, .Qpdb_in_private, .fspv_debug_EQ => .{ .unsupported = dropped_debug },
|
|
||||||
.Fc, .Cc, .Ni, .No, .Lx, .dumpbin => .{ .unsupported = dropped_disasm },
|
|
||||||
.recompile, .link, .ast_dump, .verify, .metal, .external_lib, .external_fn, .setprivate, .getprivate, .setrootsignature, .extractrootsignature, .verifyrootsignature, .rw_unchanged, .rw_skip_function_body, .rw_skip_static, .rw_global_extern_by_default, .rw_keep_user_macro, .rw_extract_entry_uniforms, .rw_remove_unused_globals, .rw_remove_unused_functions, .rw_line_directive, .rw_decl_global_cb, .import_binding_table, .binding_table_define, .ftime_report, .ftime_trace, .ftime_trace_EQ, .ftime_trace_granularity_EQ => .{ .unsupported = dropped_tooling },
|
|
||||||
.Odump, .fcgl, .print_before_all, .print_before, .print_after_all, .print_after, .opt_disable, .opt_enable, .opt_select, .memdep_block_scan_limit, .fdisable_loc_tracking, .fnew_inlining_behavior, .preserve_intermediate_values, .skip_serialization, .d_Flag, .d_Joined, .ignore_opt_semdefs, .ignore_semdef, .override_semdef, .precise_output, .disable_exception_handling, .fspv_print_all, .fspv_max_id => .{ .unsupported = dropped_internal },
|
|
||||||
|
|
||||||
else => .{ .unsupported = not_yet },
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The definition of `id` in the generated table.
|
|
||||||
pub fn info(id: Id) *const Option {
|
|
||||||
for (&table.options) |*o| if (o.id == id) return o;
|
|
||||||
unreachable;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn extraHelp(id: Extra) []const u8 {
|
|
||||||
for (extra_options) |o| if (o.id == id) return o.help;
|
|
||||||
unreachable;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `-help`: dxc's option groups, listing implemented and accepted options
|
|
||||||
/// with dxc's help text, then zdxc's own options.
|
|
||||||
pub fn printHelp(w: *std.Io.Writer, show_hidden: bool) !void {
|
|
||||||
try w.writeAll(
|
|
||||||
\\OVERVIEW: zdxc - HLSL 2021 to DXIL / SPIR-V compiler (dxc-compatible command line)
|
|
||||||
\\
|
|
||||||
\\USAGE: zdxc [options] <input>
|
|
||||||
\\
|
|
||||||
\\Options are spelled as in dxc (-T, /T, -Tcs_6_0 ...). Options dxc accepts
|
|
||||||
\\but zdxc does not implement yet are accepted with a note; dropped dxc
|
|
||||||
\\features (debug info, disassembly, linking, ...) are reported as errors.
|
|
||||||
\\
|
|
||||||
);
|
|
||||||
for (table.groups) |g| {
|
|
||||||
var printed_title = false;
|
|
||||||
for (table.options) |o| {
|
|
||||||
if (!std.mem.eql(u8, o.group, g.name) or o.alias != null) continue;
|
|
||||||
if (o.hidden and !show_hidden) continue;
|
|
||||||
if (support(o.id) == .unsupported) continue;
|
|
||||||
if (!printed_title) {
|
|
||||||
try w.print("\n{s}:\n", .{if (g.help.len > 0) g.help else g.title});
|
|
||||||
printed_title = true;
|
|
||||||
}
|
|
||||||
try printOption(w, o.spelling, o.kind, o.meta, o.help, support(o.id) == .ignored);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
try w.writeAll("\nzdxc options:\n");
|
|
||||||
for (extra_options) |o| try printOption(w, o.spelling, .flag, "", o.help, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn printOption(w: *std.Io.Writer, spelling: []const u8, kind: Kind, meta: []const u8, help: []const u8, ignored: bool) !void {
|
|
||||||
var buf: [64]u8 = undefined;
|
|
||||||
const sep: []const u8 = if (kind == .separate or kind == .multi_arg) " " else "";
|
|
||||||
const left = std.fmt.bufPrint(&buf, "-{s}{s}{s}", .{ spelling, sep, meta }) catch spelling;
|
|
||||||
try w.print(" {s}", .{left});
|
|
||||||
if (left.len < 26) try w.splatByteAll(' ', 26 - left.len) else try w.writeAll("\n ");
|
|
||||||
// dxc help text can contain newlines and tabs; keep it on one line.
|
|
||||||
for (help) |c| try w.writeByte(if (c == '\n' or c == '\t') ' ' else c);
|
|
||||||
if (ignored) try w.writeAll(" [accepted, no effect yet]");
|
|
||||||
try w.writeByte('\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
// -------------------------------------------------------------------------
|
|
||||||
// Tests
|
|
||||||
|
|
||||||
test "dxc spellings: dash, slash, joined and separate" {
|
|
||||||
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
|
||||||
defer arena.deinit();
|
|
||||||
const a = arena.allocator();
|
|
||||||
var f: Failure = .{};
|
|
||||||
const p = try parse(a, &.{ "-T", "cs_6_0", "/Emain2", "-Foout.dxo", "/Fi", "x.i", "-DA=1", "-D", "B", "-Iinc", "-WX", "/O3", "-Wno-macro-redefined", "-fvk-b-shift", "1", "0", "/Users/me/s.hlsl", "-", "-zdxc-ast" }, &f);
|
|
||||||
try std.testing.expectEqual(@as(usize, 2), p.inputs.len);
|
|
||||||
try std.testing.expectEqualStrings("/Users/me/s.hlsl", p.inputs[0]);
|
|
||||||
try std.testing.expectEqualStrings("-", p.inputs[1]);
|
|
||||||
const expect = [_]struct { Id, []const u8 }{
|
|
||||||
.{ .target_profile, "cs_6_0" }, .{ .entrypoint, "main2" }, .{ .Fo, "out.dxo" }, .{ .Fi, "x.i" },
|
|
||||||
.{ .D, "A=1" }, .{ .D, "B" }, .{ .I, "inc" }, .{ ._SLASH_WX, "" },
|
|
||||||
.{ .O3, "" }, .{ .W_Joined, "no-macro-redefined" },
|
|
||||||
};
|
|
||||||
for (expect, 0..) |e, i| {
|
|
||||||
try std.testing.expect(p.args[i].is(e[0]));
|
|
||||||
try std.testing.expectEqualStrings(e[1], p.args[i].value());
|
|
||||||
}
|
|
||||||
try std.testing.expect(p.args[10].is(.fvk_b_shift));
|
|
||||||
try std.testing.expectEqual(@as(usize, 2), p.args[10].values.len);
|
|
||||||
try std.testing.expect(p.args[11].which == .extra and p.args[11].which.extra == .zdxc_ast);
|
|
||||||
}
|
|
||||||
|
|
||||||
test "unknown and missing arguments, flags need exact matches" {
|
|
||||||
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
|
||||||
defer arena.deinit();
|
|
||||||
const a = arena.allocator();
|
|
||||||
var f: Failure = .{};
|
|
||||||
try std.testing.expectError(error.UnknownArgument, parse(a, &.{"-bogus"}, &f));
|
|
||||||
try std.testing.expectEqualStrings("-bogus", f.arg);
|
|
||||||
try std.testing.expectError(error.MissingArgument, parse(a, &.{"-T"}, &f));
|
|
||||||
try std.testing.expectEqualStrings("-T", f.arg);
|
|
||||||
// `-tcs_6_0`: options are case-sensitive, as in dxc.
|
|
||||||
try std.testing.expectError(error.UnknownArgument, parse(a, &.{"-tcs_6_0"}, &f));
|
|
||||||
// `-WXy` is not the -WX flag; it is the joined -W<warning> option.
|
|
||||||
const p = try parse(a, &.{"-WXy"}, &f);
|
|
||||||
try std.testing.expect(p.args[0].is(.W_Joined));
|
|
||||||
}
|
|
||||||
|
|
||||||
test "every option has a support level and a table entry" {
|
|
||||||
for (table.options) |o| {
|
|
||||||
_ = support(o.id);
|
|
||||||
try std.testing.expect(info(o.id).id == o.id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,8 +1,6 @@
|
||||||
//! zdxc: an HLSL 2021 compiler targeting DXIL and SPIR-V.
|
//! zdxc: an HLSL 2021 compiler targeting DXIL and SPIR-V.
|
||||||
|
|
||||||
pub const diag = @import("diag.zig");
|
pub const Diagnostics = @import("diag.zig").Diagnostics;
|
||||||
pub const options = @import("options.zig");
|
|
||||||
pub const Diagnostics = diag.Diagnostics;
|
|
||||||
|
|
||||||
pub const front = struct {
|
pub const front = struct {
|
||||||
pub const source = @import("front/source.zig");
|
pub const source = @import("front/source.zig");
|
||||||
|
|
@ -10,9 +8,6 @@ pub const front = struct {
|
||||||
pub const scan = @import("front/scan.zig");
|
pub const scan = @import("front/scan.zig");
|
||||||
pub const preproc = @import("front/preproc.zig");
|
pub const preproc = @import("front/preproc.zig");
|
||||||
pub const pp_print = @import("front/pp_print.zig");
|
pub const pp_print = @import("front/pp_print.zig");
|
||||||
pub const ast = @import("front/ast.zig");
|
|
||||||
pub const parser = @import("front/parser.zig");
|
|
||||||
pub const ast_dump = @import("front/ast_dump.zig");
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const dxil = struct {
|
pub const dxil = struct {
|
||||||
|
|
@ -35,5 +30,4 @@ test {
|
||||||
std.testing.refAllDecls(dxil);
|
std.testing.refAllDecls(dxil);
|
||||||
std.testing.refAllDecls(spirv);
|
std.testing.refAllDecls(spirv);
|
||||||
_ = @import("diag.zig");
|
_ = @import("diag.zig");
|
||||||
_ = @import("options.zig");
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Binary file not shown.
|
|
@ -1,42 +0,0 @@
|
||||||
#!/bin/sh
|
|
||||||
# Command-line oracle: every dxc invocation in the DXC test corpus (the
|
|
||||||
# arguments of each `RUN: %dxc ...` line) must be understood by zdxc's
|
|
||||||
# dxc-compatible parser. Allowed outcomes: accepted, or rejected as an
|
|
||||||
# unsupported dxc feature. "unknown argument" / "missing argument" fail.
|
|
||||||
#
|
|
||||||
# Usage: test/oracle/cli.sh <path-to-zdxc>
|
|
||||||
set -u
|
|
||||||
ZDXC=$(cd "$(dirname "$1")" && pwd)/$(basename "$1")
|
|
||||||
DXC_ROOT=${DXC_ROOT:-..}
|
|
||||||
TMP=$(mktemp -d)
|
|
||||||
trap 'rm -rf "$TMP"' EXIT
|
|
||||||
|
|
||||||
grep -rh --include='*.hlsl' 'RUN: *%dxc ' "$DXC_ROOT/tools/clang/test" > "$TMP/runs" 2>/dev/null
|
|
||||||
total=0; ok=0; unsupported=0; bad=0
|
|
||||||
while IFS= read -r line; do
|
|
||||||
# Arguments between `%dxc` and the first pipe / redirect; drop the input.
|
|
||||||
# Tokens containing lit substitutions (%s, %t, %S/...) are dropped
|
|
||||||
# whole, as are redirections.
|
|
||||||
args=$(printf '%s' "$line" | sed -E 's/.*RUN: *%dxc //; s/[0-9]?>&[0-9]//g; s/[|<>].*$//' | tr ' ' '\n' | grep -v '%' | tr '\n' ' ')
|
|
||||||
total=$((total + 1))
|
|
||||||
# -zdxc-lex on an empty file: only the command line is exercised.
|
|
||||||
# shellcheck disable=SC2086
|
|
||||||
if out=$("$ZDXC" $args -zdxc-lex "$TMP/none.hlsl" 2>&1 < /dev/null); then
|
|
||||||
ok=$((ok + 1))
|
|
||||||
elif printf '%s' "$out" | grep -q "is not supported"; then
|
|
||||||
unsupported=$((unsupported + 1))
|
|
||||||
printf '%s\n' "$out" | grep -m1 "is not supported" | sed -E "s/.*error: '([^']*)'.*/\1/" >> "$TMP/unsupported"
|
|
||||||
elif printf '%s' "$out" | grep -qE "unknown argument|is missing|more than one input"; then
|
|
||||||
bad=$((bad + 1))
|
|
||||||
echo "BAD: $args -> $(printf '%s' "$out" | head -1)"
|
|
||||||
else
|
|
||||||
ok=$((ok + 1)) # other errors (e.g. invalid values) are not parser failures
|
|
||||||
fi
|
|
||||||
done < "$TMP/runs"
|
|
||||||
: > "$TMP/none.hlsl"
|
|
||||||
if [ -s "$TMP/unsupported" ]; then
|
|
||||||
echo "unsupported options seen (count):"
|
|
||||||
sort "$TMP/unsupported" | uniq -c | sort -rn | head -${SHOW:-15}
|
|
||||||
fi
|
|
||||||
echo "oracle cli: $total dxc command lines: $ok accepted, $unsupported unsupported-feature, $bad parse failures"
|
|
||||||
[ "$bad" -eq 0 ]
|
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
#!/bin/sh
|
|
||||||
# Print the file name if dxc compiles it with its RUN-line flags (-HV 2021).
|
|
||||||
flags=$(sh "$(dirname "$0")/run_flags.sh" "$1") || exit 0
|
|
||||||
# shellcheck disable=SC2086
|
|
||||||
"$DXC" -HV 2021 $flags "$1" -Fo /dev/null >/dev/null 2>&1 && echo "$1"
|
|
||||||
exit 0
|
|
||||||
|
|
@ -1,50 +0,0 @@
|
||||||
#!/bin/sh
|
|
||||||
# Parser oracle: every corpus file that dxc compiles successfully (with the
|
|
||||||
# target and flags from its RUN line, under -HV 2021) must parse without
|
|
||||||
# syntax errors in zdxc. Prints the pass rate and the most common errors.
|
|
||||||
#
|
|
||||||
# Usage: test/oracle/parse.sh <path-to-zdxc>
|
|
||||||
# The list of dxc-valid files is cached in zig-out/oracle/parse-valid.txt;
|
|
||||||
# delete it to rebuild (takes a few minutes).
|
|
||||||
set -u
|
|
||||||
|
|
||||||
ZDXC=$(cd "$(dirname "$1")" && pwd)/$(basename "$1")
|
|
||||||
DXC_ROOT=${DXC_ROOT:-..}
|
|
||||||
DXC=$(cd "${DXC_BUILD:-$DXC_ROOT/build}" && pwd)/bin/dxc
|
|
||||||
CACHE=zig-out/oracle/parse-valid.txt
|
|
||||||
JOBS=${JOBS:-8}
|
|
||||||
mkdir -p zig-out/oracle
|
|
||||||
|
|
||||||
if [ ! -s "$CACHE" ]; then
|
|
||||||
echo "building list of dxc-valid corpus files (cached in $CACHE)..."
|
|
||||||
tmp=$(mktemp)
|
|
||||||
find "$DXC_ROOT/tools/clang/test/CodeGenHLSL" "$DXC_ROOT/tools/clang/test/CodeGenDXIL" "$DXC_ROOT/tools/clang/test/CodeGenSPIRV" -name '*.hlsl' | sort > "$tmp"
|
|
||||||
export DXC
|
|
||||||
xargs -P "$JOBS" -n 1 sh test/oracle/dxc_valid_one.sh < "$tmp" | sort > "$CACHE"
|
|
||||||
rm -f "$tmp"
|
|
||||||
fi
|
|
||||||
|
|
||||||
TMP=$(mktemp -d)
|
|
||||||
trap 'rm -rf "$TMP"' EXIT
|
|
||||||
pass=0
|
|
||||||
fail=0
|
|
||||||
while read -r f; do
|
|
||||||
flags=$(sh test/oracle/run_flags.sh "$f") || continue
|
|
||||||
# shellcheck disable=SC2086
|
|
||||||
if "$ZDXC" -zdxc-parse $flags "$f" > "$TMP/out" 2>&1; then
|
|
||||||
pass=$((pass + 1))
|
|
||||||
else
|
|
||||||
fail=$((fail + 1))
|
|
||||||
echo "$f" >> "$TMP/failed"
|
|
||||||
grep -m1 -E 'error' "$TMP/out" | sed -E 's/^.*(error|fatal): //' >> "$TMP/errors"
|
|
||||||
fi
|
|
||||||
done < "$CACHE"
|
|
||||||
|
|
||||||
if [ "$fail" -gt 0 ]; then
|
|
||||||
echo "most common first errors:"
|
|
||||||
sed -E "s/'[^']*'/'X'/g" "$TMP/errors" | sort | uniq -c | sort -rn | head -${SHOW:-15}
|
|
||||||
echo "first failing files:"
|
|
||||||
head -${SHOW_FILES:-10} "$TMP/failed"
|
|
||||||
fi
|
|
||||||
echo "oracle parse: $pass passed, $fail failed (of $(wc -l < "$CACHE" | tr -d ' ') dxc-valid files)"
|
|
||||||
[ "$fail" -eq 0 ]
|
|
||||||
|
|
@ -1,9 +0,0 @@
|
||||||
#!/bin/sh
|
|
||||||
# Print the first parse error of every dxc-valid corpus file that zdxc
|
|
||||||
# fails to parse (run test/oracle/parse.sh first to build the file list).
|
|
||||||
# Usage: test/oracle/parse_errors.sh <path-to-zdxc>
|
|
||||||
while read -r f; do
|
|
||||||
flags=$(sh test/oracle/run_flags.sh "$f") || continue
|
|
||||||
# shellcheck disable=SC2086
|
|
||||||
"$1" -zdxc-parse $flags "$f" 2>&1 | grep -m1 -E "error|fatal" | sed -E "s#^[^ ]*: (error|fatal): #$f: #"
|
|
||||||
done < zig-out/oracle/parse-valid.txt
|
|
||||||
|
|
@ -1,12 +0,0 @@
|
||||||
#!/bin/sh
|
|
||||||
# Print the dxc/zdxc flags taken from the first RUN line of an HLSL test:
|
|
||||||
# -T, -E, -D, -spirv and -enable-16bit-types. Exits 1 if there is no -T.
|
|
||||||
run=$(grep -m1 'RUN:' "$1")
|
|
||||||
target=$(printf '%s' "$run" | grep -oE -- '-T *[a-z]+_6_[0-9]+' | head -1 | sed 's/-T *//')
|
|
||||||
[ -n "$target" ] || exit 1
|
|
||||||
entry=$(printf '%s' "$run" | grep -oE -- '-E *[A-Za-z_][A-Za-z0-9_]*' | head -1 | sed 's/-E */-E /')
|
|
||||||
defs=$(printf '%s' "$run" | grep -oE -- '-D *[A-Za-z_][A-Za-z0-9_]*(=[^ ]*)?' | sed 's/-D */-D/' | tr '\n' ' ')
|
|
||||||
extra=""
|
|
||||||
printf '%s' "$run" | grep -q -- '-spirv' && extra="$extra -spirv"
|
|
||||||
printf '%s' "$run" | grep -q -- '-enable-16bit-types' && extra="$extra -enable-16bit-types"
|
|
||||||
echo "-T $target $entry $extra $defs"
|
|
||||||
|
|
@ -1,270 +0,0 @@
|
||||||
//! Build-time generator: reads dxc's option definitions
|
|
||||||
//! (vendor/dxc/HLSLOptions.td, LLVM OptParser tablegen syntax) and writes a
|
|
||||||
//! Zig table used by the dxc-compatible command-line parser.
|
|
||||||
//!
|
|
||||||
//! Usage: gen_options <HLSLOptions.td> <out.zig>
|
|
||||||
//!
|
|
||||||
//! Only the subset of tablegen used by that file is understood:
|
|
||||||
//! def NAME : Kind<[prefixes], "spelling"[, N]>, Attr<...>, ...;
|
|
||||||
//! with Group<>, Flags<[...]>, HelpText<"">, MetaVarName<"">, Alias<>.
|
|
||||||
|
|
||||||
const std = @import("std");
|
|
||||||
const Allocator = std.mem.Allocator;
|
|
||||||
|
|
||||||
const Def = struct {
|
|
||||||
name: []const u8,
|
|
||||||
kind: []const u8,
|
|
||||||
prefixes: std.ArrayList([]const u8) = .empty,
|
|
||||||
spelling: []const u8 = "",
|
|
||||||
count: u32 = 0,
|
|
||||||
group: []const u8 = "",
|
|
||||||
help: []const u8 = "",
|
|
||||||
meta: []const u8 = "",
|
|
||||||
alias: []const u8 = "",
|
|
||||||
hidden: bool = false,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub fn main(init: std.process.Init) !void {
|
|
||||||
const arena = init.arena.allocator();
|
|
||||||
const io = init.io;
|
|
||||||
const args = try init.minimal.args.toSlice(arena);
|
|
||||||
if (args.len != 3) return error.Usage;
|
|
||||||
const text = try std.Io.Dir.cwd().readFileAlloc(io, args[1], arena, .limited(1 << 20));
|
|
||||||
|
|
||||||
var p: Parser = .{ .text = text, .a = arena };
|
|
||||||
var defs: std.ArrayList(Def) = .empty;
|
|
||||||
while (try p.nextDef()) |d| try defs.append(arena, d);
|
|
||||||
|
|
||||||
var out: std.Io.Writer.Allocating = .init(arena);
|
|
||||||
try emit(&out.writer, defs.items);
|
|
||||||
try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = args[2], .data = out.written() });
|
|
||||||
}
|
|
||||||
|
|
||||||
const Parser = struct {
|
|
||||||
text: []const u8,
|
|
||||||
a: Allocator,
|
|
||||||
pos: usize = 0,
|
|
||||||
|
|
||||||
fn skipSpace(p: *Parser) void {
|
|
||||||
while (p.pos < p.text.len) {
|
|
||||||
const c = p.text[p.pos];
|
|
||||||
if (std.ascii.isWhitespace(c)) {
|
|
||||||
p.pos += 1;
|
|
||||||
} else if (std.mem.startsWith(u8, p.text[p.pos..], "//")) {
|
|
||||||
while (p.pos < p.text.len and p.text[p.pos] != '\n') p.pos += 1;
|
|
||||||
} else if (std.mem.startsWith(u8, p.text[p.pos..], "/*")) {
|
|
||||||
const end = std.mem.indexOfPos(u8, p.text, p.pos + 2, "*/") orelse p.text.len - 2;
|
|
||||||
p.pos = end + 2;
|
|
||||||
} else break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn ident(p: *Parser) []const u8 {
|
|
||||||
p.skipSpace();
|
|
||||||
const start = p.pos;
|
|
||||||
while (p.pos < p.text.len and (std.ascii.isAlphanumeric(p.text[p.pos]) or p.text[p.pos] == '_')) p.pos += 1;
|
|
||||||
return p.text[start..p.pos];
|
|
||||||
}
|
|
||||||
|
|
||||||
fn expect(p: *Parser, c: u8) !void {
|
|
||||||
p.skipSpace();
|
|
||||||
if (p.pos >= p.text.len or p.text[p.pos] != c) {
|
|
||||||
std.debug.print("gen_options: expected '{c}' at offset {d}\n", .{ c, p.pos });
|
|
||||||
return error.Syntax;
|
|
||||||
}
|
|
||||||
p.pos += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
fn peekIs(p: *Parser, c: u8) bool {
|
|
||||||
p.skipSpace();
|
|
||||||
return p.pos < p.text.len and p.text[p.pos] == c;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A double-quoted string with `\` escapes, returned unescaped.
|
|
||||||
fn string(p: *Parser) ![]const u8 {
|
|
||||||
try p.expect('"');
|
|
||||||
var buf: std.ArrayList(u8) = .empty;
|
|
||||||
while (p.pos < p.text.len and p.text[p.pos] != '"') {
|
|
||||||
var c = p.text[p.pos];
|
|
||||||
if (c == '\\' and p.pos + 1 < p.text.len) {
|
|
||||||
p.pos += 1;
|
|
||||||
c = switch (p.text[p.pos]) {
|
|
||||||
'n' => '\n',
|
|
||||||
't' => '\t',
|
|
||||||
else => p.text[p.pos],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
try buf.append(p.a, c);
|
|
||||||
p.pos += 1;
|
|
||||||
}
|
|
||||||
try p.expect('"');
|
|
||||||
return buf.items;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Skip a balanced `<...>` group we do not interpret.
|
|
||||||
fn skipAngles(p: *Parser) !void {
|
|
||||||
try p.expect('<');
|
|
||||||
var depth: u32 = 1;
|
|
||||||
while (p.pos < p.text.len and depth > 0) : (p.pos += 1) {
|
|
||||||
switch (p.text[p.pos]) {
|
|
||||||
'<' => depth += 1,
|
|
||||||
'>' => depth -= 1,
|
|
||||||
'"' => {
|
|
||||||
_ = try p.string();
|
|
||||||
p.pos -= 1;
|
|
||||||
},
|
|
||||||
else => {},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn nextDef(p: *Parser) !?Def {
|
|
||||||
while (true) {
|
|
||||||
p.skipSpace();
|
|
||||||
if (p.pos >= p.text.len) return null;
|
|
||||||
const word = p.ident();
|
|
||||||
if (word.len == 0) {
|
|
||||||
p.pos += 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (std.mem.eql(u8, word, "include")) {
|
|
||||||
_ = try p.string();
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!std.mem.eql(u8, word, "def")) continue;
|
|
||||||
var d: Def = .{ .name = p.ident(), .kind = "" };
|
|
||||||
try p.expect(':');
|
|
||||||
d.kind = p.ident();
|
|
||||||
if (p.peekIs('<')) try p.kindArgs(&d);
|
|
||||||
while (p.peekIs(',')) {
|
|
||||||
p.pos += 1;
|
|
||||||
const attr = p.ident();
|
|
||||||
try p.attribute(&d, attr);
|
|
||||||
}
|
|
||||||
try p.expect(';');
|
|
||||||
return d;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn kindArgs(p: *Parser, d: *Def) !void {
|
|
||||||
try p.expect('<');
|
|
||||||
if (std.mem.eql(u8, d.kind, "OptionGroup")) {
|
|
||||||
d.spelling = try p.string();
|
|
||||||
try p.expect('>');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try p.expect('[');
|
|
||||||
while (!p.peekIs(']')) {
|
|
||||||
try d.prefixes.append(p.a, try p.string());
|
|
||||||
if (p.peekIs(',')) p.pos += 1;
|
|
||||||
}
|
|
||||||
try p.expect(']');
|
|
||||||
try p.expect(',');
|
|
||||||
d.spelling = try p.string();
|
|
||||||
if (p.peekIs(',')) {
|
|
||||||
p.pos += 1;
|
|
||||||
p.skipSpace();
|
|
||||||
const start = p.pos;
|
|
||||||
while (p.pos < p.text.len and std.ascii.isDigit(p.text[p.pos])) p.pos += 1;
|
|
||||||
d.count = try std.fmt.parseInt(u32, p.text[start..p.pos], 10);
|
|
||||||
}
|
|
||||||
try p.expect('>');
|
|
||||||
}
|
|
||||||
|
|
||||||
fn attribute(p: *Parser, d: *Def, attr: []const u8) !void {
|
|
||||||
if (std.mem.eql(u8, attr, "HelpText")) {
|
|
||||||
try p.expect('<');
|
|
||||||
d.help = try p.string();
|
|
||||||
try p.expect('>');
|
|
||||||
} else if (std.mem.eql(u8, attr, "MetaVarName")) {
|
|
||||||
try p.expect('<');
|
|
||||||
d.meta = try p.string();
|
|
||||||
try p.expect('>');
|
|
||||||
} else if (std.mem.eql(u8, attr, "Group")) {
|
|
||||||
try p.expect('<');
|
|
||||||
d.group = p.ident();
|
|
||||||
try p.expect('>');
|
|
||||||
} else if (std.mem.eql(u8, attr, "Alias")) {
|
|
||||||
try p.expect('<');
|
|
||||||
d.alias = p.ident();
|
|
||||||
try p.expect('>');
|
|
||||||
} else if (std.mem.eql(u8, attr, "Flags")) {
|
|
||||||
const start = p.pos;
|
|
||||||
try p.skipAngles();
|
|
||||||
d.hidden = std.mem.indexOf(u8, p.text[start..p.pos], "HelpHidden") != null;
|
|
||||||
} else {
|
|
||||||
try p.skipAngles();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
fn kindTag(kind: []const u8) ?[]const u8 {
|
|
||||||
const map = [_][2][]const u8{
|
|
||||||
.{ "Flag", "flag" },
|
|
||||||
.{ "Joined", "joined" },
|
|
||||||
.{ "JoinedOrSeparate", "joined_or_separate" },
|
|
||||||
.{ "Separate", "separate" },
|
|
||||||
.{ "MultiArg", "multi_arg" },
|
|
||||||
.{ "CommaJoined", "comma_joined" },
|
|
||||||
};
|
|
||||||
for (map) |m| if (std.mem.eql(u8, m[0], kind)) return m[1];
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
fn emit(w: *std.Io.Writer, defs: []const Def) !void {
|
|
||||||
try w.writeAll(
|
|
||||||
\\//! Generated by tools/gen_options.zig from vendor/dxc/HLSLOptions.td.
|
|
||||||
\\//! Do not edit.
|
|
||||||
\\
|
|
||||||
\\pub const Kind = enum { flag, joined, joined_or_separate, separate, multi_arg, comma_joined };
|
|
||||||
\\
|
|
||||||
\\pub const Group = struct { name: []const u8, title: []const u8, help: []const u8 };
|
|
||||||
\\
|
|
||||||
\\pub const Option = struct {
|
|
||||||
\\ /// Name of the tablegen def (dxc's OPT_<id>).
|
|
||||||
\\ id: Id,
|
|
||||||
\\ kind: Kind,
|
|
||||||
\\ spelling: []const u8,
|
|
||||||
\\ dash: bool,
|
|
||||||
\\ slash: bool,
|
|
||||||
\\ dash_dash: bool,
|
|
||||||
\\ /// Number of following arguments for multi_arg options.
|
|
||||||
\\ count: u8,
|
|
||||||
\\ group: []const u8,
|
|
||||||
\\ help: []const u8,
|
|
||||||
\\ meta: []const u8,
|
|
||||||
\\ hidden: bool,
|
|
||||||
\\ alias: ?Id,
|
|
||||||
\\};
|
|
||||||
\\
|
|
||||||
\\pub const groups = [_]Group{
|
|
||||||
\\
|
|
||||||
);
|
|
||||||
for (defs) |d| {
|
|
||||||
if (!std.mem.eql(u8, d.kind, "OptionGroup")) continue;
|
|
||||||
try w.print(" .{{ .name = \"{s}\", .title = \"{f}\", .help = \"{f}\" }},\n", .{ d.name, std.zig.fmtString(d.spelling), std.zig.fmtString(d.help) });
|
|
||||||
}
|
|
||||||
try w.writeAll("};\n\npub const Id = enum {\n");
|
|
||||||
for (defs) |d| {
|
|
||||||
if (kindTag(d.kind) == null) continue;
|
|
||||||
try w.print(" {f},\n", .{std.zig.fmtId(d.name)});
|
|
||||||
}
|
|
||||||
try w.writeAll("};\n\npub const options = [_]Option{\n");
|
|
||||||
for (defs) |d| {
|
|
||||||
const tag = kindTag(d.kind) orelse continue;
|
|
||||||
var dash = false;
|
|
||||||
var slash = false;
|
|
||||||
var dash_dash = false;
|
|
||||||
for (d.prefixes.items) |pre| {
|
|
||||||
if (std.mem.eql(u8, pre, "-")) dash = true;
|
|
||||||
if (std.mem.eql(u8, pre, "/")) slash = true;
|
|
||||||
if (std.mem.eql(u8, pre, "--")) dash_dash = true;
|
|
||||||
}
|
|
||||||
try w.print(" .{{ .id = .{f}, .kind = .{s}, .spelling = \"{f}\", .dash = {}, .slash = {}, .dash_dash = {}, .count = {d}, .group = \"{s}\", .help = \"{f}\", .meta = \"{f}\", .hidden = {}, .alias = ", .{
|
|
||||||
std.zig.fmtId(d.name), tag, std.zig.fmtString(d.spelling), dash, slash, dash_dash, d.count, d.group, std.zig.fmtString(d.help), std.zig.fmtString(d.meta), d.hidden,
|
|
||||||
});
|
|
||||||
if (d.alias.len > 0) try w.print(".{f}", .{std.zig.fmtId(d.alias)}) else try w.writeAll("null");
|
|
||||||
try w.writeAll(" },\n");
|
|
||||||
}
|
|
||||||
try w.writeAll("};\n");
|
|
||||||
}
|
|
||||||
|
|
@ -5,7 +5,6 @@ Each entry records the source path and the DXC commit it was copied from.
|
||||||
|
|
||||||
| File | Source in DXC | DXC commit | License |
|
| File | Source in DXC | DXC commit | License |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| `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`) |
|
| `hlsl-headers/` (all files) | `tools/clang/lib/Headers/hlsl/` | ecb18fb18 | Apache-2.0 WITH LLVM-exception (`hlsl-headers/LICENSE.txt`) |
|
||||||
|
|
||||||
DXC is distributed under the University of Illinois/NCSA license (LICENSE.TXT
|
DXC is distributed under the University of Illinois/NCSA license (LICENSE.TXT
|
||||||
|
|
|
||||||
|
|
@ -1,616 +0,0 @@
|
||||||
//===--- HLSLOptions.td - Options for HLSL --------------------------------===//
|
|
||||||
///////////////////////////////////////////////////////////////////////////////
|
|
||||||
// //
|
|
||||||
// HLSLOptions.td //
|
|
||||||
// Copyright (C) Microsoft Corporation. All rights reserved. //
|
|
||||||
// This file is distributed under the University of Illinois Open Source //
|
|
||||||
// License. See LICENSE.TXT for details. //
|
|
||||||
// //
|
|
||||||
// This file defines the options accepted by HLSL. //
|
|
||||||
// //
|
|
||||||
///////////////////////////////////////////////////////////////////////////////
|
|
||||||
// Include the common option parsing interfaces. //
|
|
||||||
|
|
||||||
include "llvm/Option/OptParser.td"
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////////
|
|
||||||
// Flags
|
|
||||||
|
|
||||||
// DriverOption - The option is a "driver" option, and should not be forwarded
|
|
||||||
// to other tools.
|
|
||||||
def DriverOption : OptionFlag;
|
|
||||||
|
|
||||||
// CoreOption - This is considered a "core" HLSL option.
|
|
||||||
def CoreOption : OptionFlag;
|
|
||||||
|
|
||||||
// ISenseOption - This option is only supported for IntelliSense.
|
|
||||||
def ISenseOption : OptionFlag;
|
|
||||||
|
|
||||||
// RewriteOption - This is considered a "rewriter" HLSL option.
|
|
||||||
def RewriteOption : OptionFlag;
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////////
|
|
||||||
// Groups
|
|
||||||
|
|
||||||
// Meta-group for options which are only used for compilation,
|
|
||||||
// and not linking etc.
|
|
||||||
def CompileOnly_Group : OptionGroup<"<CompileOnly group>">;
|
|
||||||
|
|
||||||
def Action_Group : OptionGroup<"<action group>">;
|
|
||||||
|
|
||||||
def I_Group : OptionGroup<"<I group>">, Group<CompileOnly_Group>;
|
|
||||||
def M_Group : OptionGroup<"<M group>">, Group<CompileOnly_Group>;
|
|
||||||
def T_Group : OptionGroup<"<T group>">;
|
|
||||||
def O_Group : OptionGroup<"<O group>">, Group<CompileOnly_Group>;
|
|
||||||
def R_Group : OptionGroup<"<R group>">, Group<CompileOnly_Group>;
|
|
||||||
def R_value_Group : OptionGroup<"<R (with value) group>">, Group<R_Group>;
|
|
||||||
def W_Group : OptionGroup<"<W group>">, Group<CompileOnly_Group>, HelpText<"Warning Options">;
|
|
||||||
def W_value_Group : OptionGroup<"<W (with value) group>">, Group<W_Group>, HelpText<"Warning Options">;
|
|
||||||
def d_Group : OptionGroup<"<d group>">;
|
|
||||||
def f_Group : OptionGroup<"<f group>">, Group<CompileOnly_Group>;
|
|
||||||
def f_clang_Group : OptionGroup<"<f (clang-only) group>">, Group<CompileOnly_Group>;
|
|
||||||
def g_Group : OptionGroup<"<g group>">;
|
|
||||||
def g_flags_Group : OptionGroup<"<g flags group>">;
|
|
||||||
def i_Group : OptionGroup<"<i group>">, Group<CompileOnly_Group>;
|
|
||||||
def clang_i_Group : OptionGroup<"<clang i group>">, Group<i_Group>;
|
|
||||||
def m_Group : OptionGroup<"<m group>">, Group<CompileOnly_Group>;
|
|
||||||
def u_Group : OptionGroup<"<u group>">;
|
|
||||||
|
|
||||||
// Developer Driver Options
|
|
||||||
|
|
||||||
def internal_Group : OptionGroup<"<clang internal options>">;
|
|
||||||
def internal_driver_Group : OptionGroup<"<clang driver internal options>">,
|
|
||||||
Group<internal_Group>, HelpText<"DRIVER OPTIONS">;
|
|
||||||
def internal_debug_Group :
|
|
||||||
OptionGroup<"<clang debug/development internal options>">,
|
|
||||||
Group<internal_Group>, HelpText<"DEBUG/DEVELOPMENT OPTIONS">;
|
|
||||||
|
|
||||||
def hlslcomp_Group : OptionGroup<"HLSL Compilation">, HelpText<"Compilation Options">;
|
|
||||||
def hlsloptz_Group : OptionGroup<"HLSL Optimization">, HelpText<"Optimization Options">;
|
|
||||||
def hlslutil_Group : OptionGroup<"HLSL Utility">, HelpText<"Utility Options">;
|
|
||||||
def hlslcore_Group : OptionGroup<"HLSL Core">, HelpText<"Common Options">;
|
|
||||||
def hlslrewrite_Group : OptionGroup<"HLSL Rewriter">, HelpText<"Rewriter Options">;
|
|
||||||
|
|
||||||
def spirv_Group : OptionGroup<"SPIR-V CodeGen">, HelpText<"SPIR-V CodeGen Options">; // SPIRV Change
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////////
|
|
||||||
// Options
|
|
||||||
|
|
||||||
// The internal option ID must be a valid C++ identifier and results in a
|
|
||||||
// hlsl::options::OPT_XX enum constant for XX.
|
|
||||||
//
|
|
||||||
// See tools/clang/include/clang/Driver/Options.td for more notes.
|
|
||||||
// These options are based on those used by clang.
|
|
||||||
// fxc-based options kept for compatiblity are below.
|
|
||||||
//
|
|
||||||
// The general approach is to include only things that are in use, in the
|
|
||||||
// same order as in Options.td.
|
|
||||||
|
|
||||||
def D : JoinedOrSeparate<["-", "/"], "D">, Group<hlslcomp_Group>, Flags<[CoreOption, RewriteOption]>,
|
|
||||||
HelpText<"Define macro">;
|
|
||||||
def H : Flag<["-"], "H">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
|
|
||||||
HelpText<"Show header includes and nesting depth">;
|
|
||||||
def I : JoinedOrSeparate<["-", "/"], "I">, Group<hlslcomp_Group>, Flags<[CoreOption, RewriteOption]>,
|
|
||||||
HelpText<"Add directory to include search path">;
|
|
||||||
def O0 : Flag<["-", "/"], "O0">, Group<hlsloptz_Group>, Flags<[CoreOption]>,
|
|
||||||
HelpText<"Optimization Level 0">;
|
|
||||||
def O1 : Flag<["-", "/"], "O1">, Group<hlsloptz_Group>, Flags<[CoreOption]>,
|
|
||||||
HelpText<"Optimization Level 1">;
|
|
||||||
def O2 : Flag<["-", "/"], "O2">, Group<hlsloptz_Group>, Flags<[CoreOption]>,
|
|
||||||
HelpText<"Optimization Level 2">;
|
|
||||||
def O3 : Flag<["-", "/"], "O3">, Group<hlsloptz_Group>, Flags<[CoreOption]>,
|
|
||||||
HelpText<"Optimization Level 3 (Default)">;
|
|
||||||
def Odump : Flag<["-", "/"], "Odump">, Group<hlslcomp_Group>, Flags<[CoreOption]>,
|
|
||||||
HelpText<"Print the optimizer commands.">;
|
|
||||||
def Qunused_arguments : Flag<["-"], "Qunused-arguments">, Group<hlslcore_Group>, Flags<[CoreOption]>,
|
|
||||||
HelpText<"Don't emit warning for unused driver arguments">;
|
|
||||||
def Wall : Flag<["-"], "Wall">, Group<W_Group>, Flags<[CoreOption]>;
|
|
||||||
def Wdeprecated : Flag<["-"], "Wdeprecated">, Group<W_Group>, Flags<[CoreOption]>;
|
|
||||||
def W_Joined : Joined<["-"], "W">, Group<W_Group>, Flags<[CoreOption]>,
|
|
||||||
MetaVarName<"[no-]<warning>">, HelpText<"Enable/Disable the specified warning">;
|
|
||||||
def d_Flag : Flag<["-"], "d">, Group<d_Group>;
|
|
||||||
def d_Joined : Joined<["-"], "d">, Group<d_Group>;
|
|
||||||
//def fcolor_diagnostics : Flag<["-"], "fcolor-diagnostics">, Group<hlslcomp_Group>,
|
|
||||||
// Flags<[CoreOption, DriverOption]>, HelpText<"Use colors in diagnostics">;
|
|
||||||
def fdiagnostics_color : Flag<["-"], "fdiagnostics-color">, Group<hlslcomp_Group>,
|
|
||||||
Flags<[CoreOption, DriverOption]>;
|
|
||||||
def fdiagnostics_color_EQ : Joined<["-"], "fdiagnostics-color=">, Group<hlslcomp_Group>;
|
|
||||||
//def fansi_escape_codes : Flag<["-"], "fansi-escape-codes">, Group<f_Group>, // HLSL Change: disable ANSI escape codes
|
|
||||||
// Flags<[CoreOption, CC1Option]>, HelpText<"Use ANSI escape codes for diagnostics">;
|
|
||||||
def fconstexpr_depth_EQ : Joined<["-"], "fconstexpr-depth=">, Group<f_Group>;
|
|
||||||
def fconstexpr_steps_EQ : Joined<["-"], "fconstexpr-steps=">, Group<f_Group>;
|
|
||||||
def fconstexpr_backtrace_limit_EQ : Joined<["-"], "fconstexpr-backtrace-limit=">,
|
|
||||||
Group<f_Group>;
|
|
||||||
def fdiagnostics_format_EQ : Joined<["-"], "fdiagnostics-format=">, Group<hlslcomp_Group>,
|
|
||||||
Flags<[CoreOption]>,
|
|
||||||
HelpText<"Select diagnostic message format. Supported values: clang, msvc, mdvc-fallback, vi">;
|
|
||||||
def fdiagnostics_show_option : Flag<["-"], "fdiagnostics-show-option">, Group<hlslcomp_Group>,
|
|
||||||
Flags<[CoreOption]>, HelpText<"Print option name with mappable diagnostics">;
|
|
||||||
def fno_diagnostics_show_option : Flag<["-"], "fno-diagnostics-show-option">, Group<hlslcomp_Group>,
|
|
||||||
Flags<[CoreOption]>, HelpText<"Do not print option name with mappable diagnostics">;
|
|
||||||
def fdiagnostics_show_category_EQ : Joined<["-"], "fdiagnostics-show-category=">, Group<hlslcomp_Group>;
|
|
||||||
def ferror_limit_EQ : Joined<["-"], "ferror-limit=">, Group<hlslcomp_Group>, Flags<[CoreOption]>;
|
|
||||||
|
|
||||||
def import_binding_table : JoinedOrSeparate<["-", "/"], "import-binding-table">, Group<hlsloptz_Group>, Flags<[CoreOption, DriverOption, HelpHidden]>,
|
|
||||||
HelpText<"Import a binding table to specify resource bindings.">;
|
|
||||||
def binding_table_define : Separate<["-", "/"], "binding-table-define">, Group<hlsloptz_Group>, Flags<[CoreOption, DriverOption, HelpHidden]>,
|
|
||||||
HelpText<"Import a binding table from a define to specify resource bindings.">;
|
|
||||||
|
|
||||||
def funsafe_math_optimizations : Flag<["-"], "funsafe-math-optimizations">,
|
|
||||||
Group<hlsloptz_Group>;
|
|
||||||
def fno_unsafe_math_optimizations : Flag<["-"], "fno-unsafe-math-optimizations">,
|
|
||||||
Group<hlsloptz_Group>;
|
|
||||||
def fassociative_math : Flag<["-"], "fassociative-math">, Group<hlsloptz_Group>;
|
|
||||||
def fno_associative_math : Flag<["-"], "fno-associative-math">, Group<hlsloptz_Group>;
|
|
||||||
//def freciprocal_math :
|
|
||||||
// Flag<["-"], "freciprocal-math">, Group<hlsloptz_Group>, Flags<[CoreOption]>,
|
|
||||||
// HelpText<"Allow division operations to be reassociated">;
|
|
||||||
def fno_reciprocal_math : Flag<["-"], "fno-reciprocal-math">, Group<hlsloptz_Group>;
|
|
||||||
def ffinite_math_only: Flag<["-"], "ffinite-math-only">, Group<hlsloptz_Group>, Flags<[CoreOption]>,
|
|
||||||
HelpText<"Allow optimizations for floating-point arithmetic that assume that arguments and results are not NaNs or +-Infs.">;
|
|
||||||
def fno_finite_math_only: Flag<["-"], "fno-finite-math-only">, Group<hlsloptz_Group>, Flags<[CoreOption]>,
|
|
||||||
HelpText<"Disallow optimizations for floating-point arithmetic that assume that arguments and results are not NaNs or +-Infs.">;
|
|
||||||
def fsigned_zeros : Flag<["-"], "fsigned-zeros">, Group<hlsloptz_Group>;
|
|
||||||
//def fno_signed_zeros :
|
|
||||||
// Flag<["-"], "fno-signed-zeros">, Group<hlsloptz_Group>, Flags<[CoreOption]>,
|
|
||||||
// HelpText<"Allow optimizations that ignore the sign of floating point zeros">;
|
|
||||||
def fhonor_nans : Flag<["-"], "fhonor-nans">, Group<hlsloptz_Group>;
|
|
||||||
def fno_honor_nans : Flag<["-"], "fno-honor-nans">, Group<hlsloptz_Group>;
|
|
||||||
def fhonor_infinities : Flag<["-"], "fhonor-infinities">, Group<hlsloptz_Group>;
|
|
||||||
def fno_honor_infinities : Flag<["-"], "fno-honor-infinities">, Group<hlsloptz_Group>;
|
|
||||||
//def ftrapping_math : Flag<["-"], "ftrapping-math">, Group<f_Group>;
|
|
||||||
//def fno_trapping_math : Flag<["-"], "fno-trapping-math">, Group<f_Group>;
|
|
||||||
//def ffp_contract : Joined<["-"], "ffp-contract=">, Group<hlsloptz_Group>,
|
|
||||||
// Flags<[CoreOption]>, HelpText<"Form fused FP ops (e.g. FMAs): fast (everywhere)"
|
|
||||||
// " | on (according to FP_CONTRACT pragma, default) | off (never fuse)">;
|
|
||||||
def flimited_precision_EQ : Joined<["-"], "flimited-precision=">, Group<hlsloptz_Group>;
|
|
||||||
def memdep_block_scan_limit : Separate<["-", "/"], "memdep-block-scan-limit">, Group<hlsloptz_Group>, Flags<[CoreOption, DriverOption, HelpHidden]>,
|
|
||||||
HelpText<"The number of instructions to scan in a block in memory dependency analysis.">;
|
|
||||||
def opt_disable : Separate<["-", "/"], "opt-disable">, Group<hlsloptz_Group>, Flags<[CoreOption, DriverOption, HelpHidden]>,
|
|
||||||
HelpText<"Disable this optimization.">;
|
|
||||||
def opt_enable : Separate<["-", "/"], "opt-enable">, Group<hlsloptz_Group>, Flags<[CoreOption, DriverOption, HelpHidden]>,
|
|
||||||
HelpText<"Enable this optimization.">;
|
|
||||||
def opt_select : MultiArg<["-", "/"], "opt-select", 2>, MetaVarName<"<opt> <variant>">, Group<hlsloptz_Group>, Flags<[CoreOption, DriverOption, HelpHidden]>,
|
|
||||||
HelpText<"Select this optimization variant.">;
|
|
||||||
|
|
||||||
def fdisable_loc_tracking : Flag<["-"], "fdisable-loc-tracking">,
|
|
||||||
Group<hlslcomp_Group>, Flags<[CoreOption]>,
|
|
||||||
HelpText<"Disable source location tracking in IR. This will break diagnostic generation for late validation. (Ignored if /Zi is passed)">;
|
|
||||||
|
|
||||||
def fnew_inlining_behavior : Flag<["-"], "fnew-inlining-behavior">,
|
|
||||||
Group<hlslcomp_Group>, Flags<[CoreOption]>,
|
|
||||||
HelpText<"Experimental option to use heuristics-driven late inlining and disable alwaysinline annotation for library shaders">;
|
|
||||||
|
|
||||||
|
|
||||||
def ftime_report : Flag<["-"], "ftime-report">, Group<hlslcomp_Group>, Flags<[CoreOption]>, HelpText<"Print time report">;
|
|
||||||
def ftime_trace : Flag<["-"], "ftime-trace">,
|
|
||||||
Group<hlslcomp_Group>, Flags<[CoreOption]>,
|
|
||||||
HelpText<"Print hierchial time tracing to stdout">;
|
|
||||||
def ftime_trace_EQ : Joined<["-"], "ftime-trace=">,
|
|
||||||
Group<hlslcomp_Group>, Flags<[CoreOption]>,
|
|
||||||
HelpText<"Print hierchial time tracing to file">;
|
|
||||||
def ftime_trace_granularity_EQ : Joined<["-"], "ftime-trace-granularity=">,
|
|
||||||
Group<hlslcomp_Group>, Flags<[CoreOption]>,
|
|
||||||
HelpText<"Minimum time granularity (in microseconds) traced by time profiler">;
|
|
||||||
|
|
||||||
def verify : Joined<["-"], "verify">,
|
|
||||||
Group<hlslcomp_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Verify diagnostic output using comment directives">;
|
|
||||||
|
|
||||||
def verbose : Flag<["-"], "verbose">,
|
|
||||||
Group<hlslcomp_Group>,
|
|
||||||
Flags<[DriverOption]>,
|
|
||||||
HelpText<"Allow emission of verbose compiler information">;
|
|
||||||
|
|
||||||
// Short alias '-v' for the verbose option
|
|
||||||
def v : Flag<["-"], "v">,
|
|
||||||
Alias<verbose>,
|
|
||||||
Group<hlslcomp_Group>,
|
|
||||||
Flags<[DriverOption]>,
|
|
||||||
HelpText<"Alias for -verbose">;
|
|
||||||
|
|
||||||
/*
|
|
||||||
def fno_caret_diagnostics : Flag<["-"], "fno-caret-diagnostics">, Group<hlslcomp_Group>,
|
|
||||||
Flags<[CoreOption]>;
|
|
||||||
def fno_color_diagnostics : Flag<["-"], "fno-color-diagnostics">, Group<hlslcomp_Group>,
|
|
||||||
Flags<[CoreOption]>;
|
|
||||||
def fno_diagnostics_color : Flag<["-"], "fno-diagnostics-color">, Group<hlslcomp_Group>,
|
|
||||||
Flags<[CoreOption, DriverOption]>;
|
|
||||||
def fno_show_column : Flag<["-"], "fno-show-column">, Group<hlslcomp_Group>, Flags<[CoreOption]>,
|
|
||||||
HelpText<"Do not include column number on diagnostics">;
|
|
||||||
def fno_spell_checking : Flag<["-"], "fno-spell-checking">, Group<hlslcomp_Group>,
|
|
||||||
Flags<[CoreOption]>, HelpText<"Disable spell-checking">;
|
|
||||||
def fshow_column : Flag<["-"], "fshow-column">, Group<hlslcomp_Group>, Flags<[CoreOption]>;
|
|
||||||
def fshow_source_location : Flag<["-"], "fshow-source-location">, Group<hlslcomp_Group>;
|
|
||||||
def fspell_checking : Flag<["-"], "fspell-checking">, Group<hlslcomp_Group>;
|
|
||||||
def fspell_checking_limit_EQ : Joined<["-"], "fspell-checking-limit=">, Group<hlslcomp_Group>;
|
|
||||||
def funroll_loops : Flag<["-"], "funroll-loops">, Group<hlsloptz_Group>,
|
|
||||||
HelpText<"Turn on loop unroller">, Flags<[CoreOption]>;
|
|
||||||
def fno_unroll_loops : Flag<["-"], "fno-unroll-loops">, Group<hlsloptz_Group>,
|
|
||||||
HelpText<"Turn off loop unroller">, Flags<[CoreOption]>;
|
|
||||||
def freroll_loops : Flag<["-"], "freroll-loops">, Group<hlsloptz_Group>,
|
|
||||||
HelpText<"Turn on loop reroller">, Flags<[CoreOption]>;
|
|
||||||
def fno_reroll_loops : Flag<["-"], "fno-reroll-loops">, Group<hlsloptz_Group>,
|
|
||||||
HelpText<"Turn off loop reroller">;
|
|
||||||
*/
|
|
||||||
def help : Flag<["-", "--", "/"], "help">, Flags<[DriverOption]>, Group<hlslcore_Group>,
|
|
||||||
HelpText<"Display available options">;
|
|
||||||
/*
|
|
||||||
def imacros : JoinedOrSeparate<["-", "--"], "imacros">, Group<clang_i_Group>, Flags<[CoreOption]>,
|
|
||||||
HelpText<"Include macros from file before parsing">, MetaVarName<"<file>">;
|
|
||||||
def include_ : JoinedOrSeparate<["-", "--"], "include">, Group<clang_i_Group>, EnumName<"include">,
|
|
||||||
MetaVarName<"<file>">, HelpText<"Include file before parsing">, Flags<[CoreOption]>;
|
|
||||||
def mllvm : Separate<["-"], "mllvm">, Flags<[CoreOption]>,
|
|
||||||
HelpText<"Additional arguments to forward to LLVM's option processing">;
|
|
||||||
def mms_bitfields : Flag<["-"], "mms-bitfields">, Group<m_Group>, Flags<[CoreOption]>,
|
|
||||||
HelpText<"Set the default structure layout to be compatible with the Microsoft compiler standard">;
|
|
||||||
def o : JoinedOrSeparate<["-"], "o">, Flags<[DriverOption, RenderAsInput, CoreOption]>,
|
|
||||||
HelpText<"Write output to <file>">, MetaVarName<"<file>">;
|
|
||||||
def time : Flag<["-"], "time">,
|
|
||||||
HelpText<"Time individual commands">;
|
|
||||||
// def U : JoinedOrSeparate<["-"], "U">, Group<CompileOnly_Group>, Flags<[CoreOption]>;
|
|
||||||
def w : Flag<["-"], "w">, HelpText<"Suppress all warnings">, Flags<[CoreOption]>;
|
|
||||||
def working_directory : JoinedOrSeparate<["-"], "working-directory">, Flags<[CoreOption]>,
|
|
||||||
MetaVarName<"<dir>">, HelpText<"Resolve file paths relative to the specified directory">;
|
|
||||||
def working_directory_EQ : Joined<["-"], "working-directory=">, Flags<[CoreOption]>,
|
|
||||||
MetaVarName<"<dir>">, Alias<working_directory>;
|
|
||||||
*/
|
|
||||||
|
|
||||||
// Double dash options, which are usually an alias for one of the previous
|
|
||||||
// options.
|
|
||||||
|
|
||||||
def _all_warnings : Flag<["--"], "all-warnings">, Flags<[CoreOption]>, Alias<Wall>;
|
|
||||||
def _help_hidden : Flag<["--"], "help-hidden">, Flags<[DriverOption]>;
|
|
||||||
def _help_question : Flag<["-", "/"], "?">, Flags<[DriverOption]>, Alias<help>;
|
|
||||||
def _version : Flag<["--"], "version">, Group<hlslcore_Group>, Flags<[DriverOption]>,
|
|
||||||
HelpText<"Display compiler version information">;
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////////
|
|
||||||
// New HLSL-specific flags.
|
|
||||||
|
|
||||||
def ast_dump : Flag<["-", "/"], "ast-dump">, Flags<[CoreOption, DriverOption, HelpHidden]>,
|
|
||||||
HelpText<"Dumps the parsed Abstract Syntax Tree.">; // should not be core, but handy workaround until explicit API written
|
|
||||||
def ast_dump_implicit : Flag<["-", "/"], "ast-dump-implicit">, Flags<[CoreOption, DriverOption, HelpHidden]>,
|
|
||||||
HelpText<"Dumps the parsed Abstract Syntax Tree, including implicit top-level decls.">;
|
|
||||||
def dump_dependencies : Flag<["-", "/"], "M">, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Dumps the list of the compilation target dependencies.">;
|
|
||||||
def write_dependencies : Flag<["-", "/"], "MD">, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Write a file with .d extension that will contain the list of the compilation target dependencies.">;
|
|
||||||
def write_dependencies_to : JoinedOrSeparate<["-", "/"], "MF">, MetaVarName<"<file>">, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Write the specified file that will contain the list of the compilation target dependencies.">;
|
|
||||||
def external_lib : Separate<["-", "/"], "external">, Group<hlslcore_Group>, Flags<[DriverOption, RewriteOption, HelpHidden]>,
|
|
||||||
HelpText<"External DLL name to load for compiler support">;
|
|
||||||
def external_fn : Separate<["-", "/"], "external-fn">, Group<hlslcore_Group>, Flags<[DriverOption, RewriteOption, HelpHidden]>,
|
|
||||||
HelpText<"External function name to load for compiler support">;
|
|
||||||
def fcgl : Flag<["-", "/"], "fcgl">, Group<hlslcore_Group>, Flags<[CoreOption, HelpHidden]>,
|
|
||||||
HelpText<"Generate high-level code only">;
|
|
||||||
def preserve_intermediate_values : Flag<["-", "/"], "preserve-intermediate-values">, Group<hlslcore_Group>, Flags<[CoreOption, HelpHidden]>,
|
|
||||||
HelpText<"Preserve intermediate values to help shader debugging">;
|
|
||||||
def flegacy_macro_expansion : Flag<["-", "/"], "flegacy-macro-expansion">, Group<hlslcomp_Group>, Flags<[CoreOption, RewriteOption, DriverOption]>,
|
|
||||||
HelpText<"Expand the operands before performing token-pasting operation (fxc behavior)">;
|
|
||||||
def flegacy_resource_reservation : Flag<["-", "/"], "flegacy-resource-reservation">, Group<hlslcomp_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Reserve unused explicit register assignments for compatibility with shader model 5.0 and below">;
|
|
||||||
def no_legacy_cbuf_layout : Flag<["-", "/"], "no-legacy-cbuf-layout">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
|
|
||||||
HelpText<"Do not use legacy cbuffer load">;
|
|
||||||
def not_use_legacy_cbuf_load_ : Flag<["-", "/"], "not_use_legacy_cbuf_load">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
|
|
||||||
HelpText<"Do not use legacy cbuffer load">;
|
|
||||||
def pack_prefix_stable : Flag<["-", "/"], "pack-prefix-stable">, Group<hlslcomp_Group>, Flags<[CoreOption]>,
|
|
||||||
HelpText<"(default) Pack signatures preserving prefix-stable property - appended elements will not disturb placement of prior elements">;
|
|
||||||
def pack_prefix_stable_ : Flag<["-", "/"], "pack_prefix_stable">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
|
|
||||||
HelpText<"(default) Pack signatures preserving prefix-stable property - appended elements will not disturb placement of prior elements">;
|
|
||||||
def pack_optimized : Flag<["-", "/"], "pack-optimized">, Group<hlslcomp_Group>, Flags<[CoreOption]>,
|
|
||||||
HelpText<"Optimize signature packing assuming identical signature provided for each connecting stage">;
|
|
||||||
def pack_optimized_ : Flag<["-", "/"], "pack_optimized">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
|
|
||||||
HelpText<"Optimize signature packing assuming identical signature provided for each connecting stage">;
|
|
||||||
def hlsl_version : Separate<["-", "/"], "HV">, Group<hlslcomp_Group>, Flags<[CoreOption, RewriteOption]>,
|
|
||||||
HelpText<"HLSL version (2016, 2017, 2018, 2021). Default is 2021">;
|
|
||||||
def no_warnings : Flag<["-", "/"], "no-warnings">, Group<hlslcomp_Group>, Flags<[CoreOption, RewriteOption]>,
|
|
||||||
HelpText<"Suppress warnings">;
|
|
||||||
def rootsig_define : Separate<["-", "/"], "rootsig-define">, Group<hlslcomp_Group>, Flags<[CoreOption]>,
|
|
||||||
HelpText<"Read root signature from a #define">;
|
|
||||||
def enable_16bit_types: Flag<["-", "/"], "enable-16bit-types">, Flags<[CoreOption, RewriteOption, DriverOption]>, Group<hlslcomp_Group>,
|
|
||||||
HelpText<"Enable 16bit types and disable min precision types. Available in HLSL 2018 and shader model 6.2">;
|
|
||||||
def ignore_line_directives : Flag<["-", "/"], "ignore-line-directives">, HelpText<"Ignore line directives">, Flags<[CoreOption]>, Group<hlslcomp_Group>;
|
|
||||||
def auto_binding_space : Separate<["-", "/"], "auto-binding-space">, Group<hlslcomp_Group>, Flags<[CoreOption]>,
|
|
||||||
HelpText<"Set auto binding space - enables auto resource binding in libraries">;
|
|
||||||
def exports : Separate<["-", "/"], "exports">, Group<hlslcomp_Group>, Flags<[CoreOption]>,
|
|
||||||
HelpText<"Specify exports when compiling a library: export1[[,export1_clone,...]=internal_name][;...]">;
|
|
||||||
def export_shaders_only : Flag<["-", "/"], "export-shaders-only">, Group<hlslcomp_Group>, Flags<[CoreOption]>,
|
|
||||||
HelpText<"Only export shaders when compiling a library">;
|
|
||||||
def default_linkage : Separate<["-", "/"], "default-linkage">, Group<hlslcomp_Group>, Flags<[CoreOption]>,
|
|
||||||
HelpText<"Set default linkage for non-shader functions when compiling or linking to a library target (internal, external)">;
|
|
||||||
def precise_output : Separate<["-", "/"], "precise-output">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
|
|
||||||
HelpText<"Mark output semantic as precise">;
|
|
||||||
def encoding : Separate<["-", "/"], "encoding">, Group<hlslcomp_Group>, Flags<[CoreOption, RewriteOption, DriverOption]>,
|
|
||||||
HelpText<"Set default encoding for source inputs and text outputs (utf8|utf16(win)|utf32(*nix)|wide) default=utf8">;
|
|
||||||
def validator_version : Separate<["-", "/"], "validator-version">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
|
|
||||||
HelpText<"Override validator version for module. Format: <major.minor> ; Default: DXIL.dll version or current internal version.">;
|
|
||||||
def print_before_all : Flag<["-", "/"], "print-before-all">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
|
|
||||||
HelpText<"Print LLVM IR before each pass.">;
|
|
||||||
def print_before : Separate<["-", "/"], "print-before">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
|
|
||||||
HelpText<"Print LLVM IR before a specific pass. May be specificied multiple times.">;
|
|
||||||
def print_after_all : Flag<["-", "/"], "print-after-all">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
|
|
||||||
HelpText<"Print LLVM IR after each pass.">;
|
|
||||||
def print_after : Separate<["-", "/"], "print-after">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
|
|
||||||
HelpText<"Print LLVM IR after a specific pass. May be specificied multiple times.">;
|
|
||||||
def ignore_opt_semdefs : Flag<["-", "/"], "ignore-opt-semdefs">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
|
|
||||||
HelpText<"Ignore optional semantic defines which are not required to ensure program correctness.">;
|
|
||||||
def ignore_semdef : Separate<["-", "/"], "ignore-semdef">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
|
|
||||||
HelpText<"Ignore the semantic define passed as a value to this flag.">;
|
|
||||||
def override_semdef : Separate<["-", "/"], "override-semdef">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
|
|
||||||
HelpText<"Override the value of semantic define with the one passed with this flag.">;
|
|
||||||
def force_zero_store_lifetimes : Flag<["-", "/"], "force-zero-store-lifetimes">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
|
|
||||||
HelpText<"Instead of generating lifetime intrinsics (SM >= 6.6) or storing undef (SM < 6.6), force fall back to storing zeroinitializer.">;
|
|
||||||
def enable_lifetime_markers : Flag<["-", "/"], "enable-lifetime-markers">, Group<hlslcomp_Group>, Flags<[CoreOption]>,
|
|
||||||
HelpText<"Enable generation of lifetime markers">;
|
|
||||||
def disable_lifetime_markers : Flag<["-", "/"], "disable-lifetime-markers">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
|
|
||||||
HelpText<"Disable generation of lifetime markers where they would be otherwise (6.6+)">;
|
|
||||||
def enable_payload_qualifiers : Flag<["-", "/"], "enable-payload-qualifiers">, Group<hlslcomp_Group>, Flags<[CoreOption, RewriteOption, DriverOption]>,
|
|
||||||
HelpText<"Enables support for payload access qualifiers for raytracing payloads in SM 6.6.">;
|
|
||||||
def disable_payload_qualifiers : Flag<["-", "/"], "disable-payload-qualifiers">, Group<hlslcomp_Group>, Flags<[CoreOption, RewriteOption, DriverOption]>,
|
|
||||||
HelpText<"Disables support for payload access qualifiers for raytracing payloads in SM 6.7.">;
|
|
||||||
def disable_exception_handling : Flag<["-", "/"], "disable-exception-handling">, Group<hlslcomp_Group>, Flags<[DriverOption, HelpHidden]>,
|
|
||||||
HelpText<"Disable dxc handling of exceptions">;
|
|
||||||
|
|
||||||
// Used with API only
|
|
||||||
def skip_serialization : Flag<["-", "/"], "skip-serialization">, Group<hlslcore_Group>, Flags<[CoreOption, HelpHidden]>,
|
|
||||||
HelpText<"Return a module interface instead of serialized output">;
|
|
||||||
|
|
||||||
def metal : Flag<["-"], "metal">,
|
|
||||||
Group<spirv_Group>,
|
|
||||||
Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Generate Metal code">;
|
|
||||||
|
|
||||||
// SPIRV Change Starts
|
|
||||||
def spirv : Flag<["-"], "spirv">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Generate SPIR-V code">;
|
|
||||||
def fvk_stage_io_order_EQ : Joined<["-"], "fvk-stage-io-order=">, Group<spirv_Group>, Flags<[CoreOption, DriverOption, HelpHidden]>,
|
|
||||||
HelpText<"Specify Vulkan stage I/O location assignment order">;
|
|
||||||
def fvk_b_shift : MultiArg<["-"], "fvk-b-shift", 2>, MetaVarName<"<shift> <space>">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Specify Vulkan binding number shift for b-type register">;
|
|
||||||
def fvk_t_shift : MultiArg<["-"], "fvk-t-shift", 2>, MetaVarName<"<shift> <space>">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Specify Vulkan binding number shift for t-type register">;
|
|
||||||
def fvk_s_shift : MultiArg<["-"], "fvk-s-shift", 2>, MetaVarName<"<shift> <space>">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Specify Vulkan binding number shift for s-type register">;
|
|
||||||
def fvk_u_shift : MultiArg<["-"], "fvk-u-shift", 2>, MetaVarName<"<shift> <space>">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Specify Vulkan binding number shift for u-type register">;
|
|
||||||
def fvk_bind_globals : MultiArg<["-"], "fvk-bind-globals", 2>, MetaVarName<"<binding> <set>">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Specify Vulkan binding number and set number for the $Globals cbuffer">;
|
|
||||||
def fvk_bind_register : MultiArg<["-"], "fvk-bind-register", 4>, MetaVarName<"<type-number> <space> <binding> <set>">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Specify Vulkan descriptor set and binding for a specific register">;
|
|
||||||
def vkbr : MultiArg<["-"], "vkbr", 4>, Flags<[CoreOption, DriverOption]>, Alias<fvk_bind_register>;
|
|
||||||
def fvk_invert_y: Flag<["-"], "fvk-invert-y">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Negate SV_Position.y before writing to stage output in VS/DS/GS/MS/Lib to accommodate Vulkan's coordinate system">;
|
|
||||||
def fvk_use_dx_position_w: Flag<["-"], "fvk-use-dx-position-w">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Reciprocate SV_Position.w after reading from stage input in PS to accommodate the difference between Vulkan and DirectX">;
|
|
||||||
def fvk_support_nonzero_base_instance: Flag<["-"], "fvk-support-nonzero-base-instance">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Follow Vulkan spec to use gl_BaseInstance as the first vertex instance, which makes SV_InstanceID = gl_InstanceIndex - gl_BaseInstance (without this option, SV_InstanceID = gl_InstanceIndex)">;
|
|
||||||
def fvk_support_nonzero_base_vertex: Flag<["-"], "fvk-support-nonzero-base-vertex">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Follow Vulkan spec to use gl_BaseVertex as the first vertex, which makes SV_VertexID = gl_VertexIndex - gl_BaseVertex (without this option, SV_VertexID = gl_VertexIndex)">;
|
|
||||||
def fvk_use_gl_layout: Flag<["-"], "fvk-use-gl-layout">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Use strict OpenGL std140/std430 memory layout for Vulkan resources">;
|
|
||||||
def fvk_use_dx_layout: Flag<["-"], "fvk-use-dx-layout">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Use DirectX memory layout for Vulkan resources">;
|
|
||||||
def fvk_use_scalar_layout: Flag<["-"], "fvk-use-scalar-layout">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Use scalar memory layout for Vulkan resources">;
|
|
||||||
def fspv_use_legacy_buffer_matrix_order: Flag<["-"], "fspv-use-legacy-buffer-matrix-order">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Assume the legacy matrix order (row major) when accessing raw buffers (e.g., ByteAdddressBuffer)">;
|
|
||||||
def fspv_reflect: Flag<["-"], "fspv-reflect">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Emit additional SPIR-V instructions to aid reflection">;
|
|
||||||
def fspv_debug_EQ : Joined<["-"], "fspv-debug=">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Specify whitelist of debug info category (file -> source -> line, tool, vulkan-with-source)">;
|
|
||||||
def fspv_extension_EQ : Joined<["-"], "fspv-extension=">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Specify SPIR-V extension permitted to use">;
|
|
||||||
def fspv_target_env_EQ : Joined<["-"], "fspv-target-env=">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Specify the target environment: vulkan1.0 (default), vulkan1.1, vulkan1.1spirv1.4, vulkan1.2, vulkan1.3, or universal1.5">;
|
|
||||||
def fspv_flatten_resource_arrays: Flag<["-"], "fspv-flatten-resource-arrays">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Flatten arrays of resources so each array element takes one binding number">;
|
|
||||||
def fspv_reduce_load_size: Flag<["-"], "fspv-reduce-load-size">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Replaces loads of composite objects to reduce memory pressure for the loads">;
|
|
||||||
def fspv_fix_func_call_arguments: Flag<["-"], "fspv-fix-func-call-arguments">, Group<spirv_Group>, Flags<[CoreOption, DriverOption, HelpHidden]>,
|
|
||||||
HelpText<"Fix function call arguments which are not memory objects">;
|
|
||||||
def fspv_entrypoint_name_EQ : Joined<["-"], "fspv-entrypoint-name=">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Specify the SPIR-V entry point name. Defaults to the HLSL entry point name.">;
|
|
||||||
def fspv_enable_maximal_reconvergence: Flag<["-"], "fspv-enable-maximal-reconvergence">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Enables the MaximallyReconvergesKHR execution mode for this module.">;
|
|
||||||
def fspv_use_vulkan_memory_model: Flag<["-"], "fspv-use-vulkan-memory-model">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Generates SPIR-V modules that use the Vulkan memory model instead of GLSL450.">;
|
|
||||||
def fspv_use_unknown_image_format
|
|
||||||
: Flag<["-"], "fspv-use-unknown-image-format">,
|
|
||||||
Group<spirv_Group>,
|
|
||||||
Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"For storage images and texel buffers, sets the default format to 'Unknown' when not specified via the `vk::image_format` attribute. If this option is not used, the format is inferred from the resource's data type.">;
|
|
||||||
|
|
||||||
def fvk_auto_shift_bindings: Flag<["-"], "fvk-auto-shift-bindings">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Apply fvk-*-shift to resources without an explicit register assignment.">;
|
|
||||||
def Wno_vk_ignored_features : Joined<["-"], "Wno-vk-ignored-features">, Group<spirv_Group>, Flags<[CoreOption, DriverOption, HelpHidden]>,
|
|
||||||
HelpText<"Do not emit warnings for ignored features resulting from no Vulkan support">;
|
|
||||||
def Wno_vk_emulated_features : Joined<["-"], "Wno-vk-emulated-features">, Group<spirv_Group>, Flags<[CoreOption, DriverOption, HelpHidden]>,
|
|
||||||
HelpText<"Do not emit warnings for emulated features resulting from no direct mapping">;
|
|
||||||
def fspv_print_all: Flag<["-"], "fspv-print-all">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Print the SPIR-V module before each pass and after the last one. Useful for debugging SPIR-V legalization and optimization passes.">;
|
|
||||||
def fspv_use_emulated_heap
|
|
||||||
: Flag<["-"], "fspv-use-emulated-heap">,
|
|
||||||
Group<spirv_Group>,
|
|
||||||
Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<
|
|
||||||
"Use emulated descriptor heap using descriptor indexing (default).">;
|
|
||||||
def fspv_use_descriptor_heap
|
|
||||||
: Flag<["-"], "fspv-use-descriptor-heap">,
|
|
||||||
Group<spirv_Group>,
|
|
||||||
Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Use SPV_EXT_descriptor_heap for HLSL descriptor heaps.">;
|
|
||||||
def Oconfig : CommaJoined<["-"], "Oconfig=">, Group<spirv_Group>, Flags<[CoreOption]>,
|
|
||||||
HelpText<"Specify a comma-separated list of SPIRV-Tools passes to customize optimization configuration (see http://khr.io/hlsl2spirv#optimization)">;
|
|
||||||
def fspv_preserve_bindings : Flag<["-"], "fspv-preserve-bindings">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Preserves all bindings declared within the module, even when those bindings are unused">;
|
|
||||||
def fspv_preserve_interface : Flag<["-"], "fspv-preserve-interface">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Preserves all interface variables in the entry point, even when those variables are unused">;
|
|
||||||
def fspv_max_id : MultiArg<["-"], "fspv-max-id", 1>, MetaVarName<"<shift> <space>">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Set the maximum value for an id in the SPIR-V binary. Default is 0x3FFFFF, which is the largest value all drivers must support.">;
|
|
||||||
def fvk_bind_resource_heap : MultiArg<["-"], "fvk-bind-resource-heap", 2>, MetaVarName<"<binding> <set>">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Specify Vulkan binding number and set number for the resource heap.">;
|
|
||||||
def fvk_bind_sampler_heap : MultiArg<["-"], "fvk-bind-sampler-heap", 2>, MetaVarName<"<binding> <set>">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Specify Vulkan binding number and set number for the sampler heap.">;
|
|
||||||
def fvk_bind_counter_heap : MultiArg<["-"], "fvk-bind-counter-heap", 2>, MetaVarName<"<binding> <set>">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
|
|
||||||
HelpText<"Specify Vulkan binding number and set number for the counter heap.">;
|
|
||||||
// SPIRV Change Ends
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////////
|
|
||||||
// fxc-based flags that don't match those previously defined.
|
|
||||||
|
|
||||||
def target_profile : JoinedOrSeparate<["-", "/"], "T">, Flags<[CoreOption]>, Group<hlslcomp_Group>, MetaVarName<"<profile>">,
|
|
||||||
/* <py::lines('VALRULE-TEXT')>hctdb_instrhelp.get_target_profiles()</py>*/
|
|
||||||
// VALRULE-TEXT:BEGIN
|
|
||||||
HelpText<"Set target profile. \n\t<profile>: ps_6_0, ps_6_1, ps_6_2, ps_6_3, ps_6_4, ps_6_5, ps_6_6, ps_6_7, ps_6_8, ps_6_9, ps_6_10, ps_6_11, \n\t\t vs_6_0, vs_6_1, vs_6_2, vs_6_3, vs_6_4, vs_6_5, vs_6_6, vs_6_7, vs_6_8, vs_6_9, vs_6_10, vs_6_11, \n\t\t gs_6_0, gs_6_1, gs_6_2, gs_6_3, gs_6_4, gs_6_5, gs_6_6, gs_6_7, gs_6_8, gs_6_9, gs_6_10, gs_6_11, \n\t\t hs_6_0, hs_6_1, hs_6_2, hs_6_3, hs_6_4, hs_6_5, hs_6_6, hs_6_7, hs_6_8, hs_6_9, hs_6_10, hs_6_11, \n\t\t ds_6_0, ds_6_1, ds_6_2, ds_6_3, ds_6_4, ds_6_5, ds_6_6, ds_6_7, ds_6_8, ds_6_9, ds_6_10, ds_6_11, \n\t\t cs_6_0, cs_6_1, cs_6_2, cs_6_3, cs_6_4, cs_6_5, cs_6_6, cs_6_7, cs_6_8, cs_6_9, cs_6_10, cs_6_11, \n\t\t lib_6_1, lib_6_2, lib_6_3, lib_6_4, lib_6_5, lib_6_6, lib_6_7, lib_6_8, lib_6_9, lib_6_10, lib_6_11, \n\t\t ms_6_5, ms_6_6, ms_6_7, ms_6_8, ms_6_9, ms_6_10, ms_6_11, \n\t\t as_6_5, as_6_6, as_6_7, as_6_8, as_6_9, as_6_10, as_6_11, \n\t\t ">;
|
|
||||||
// VALRULE-TEXT:END
|
|
||||||
def entrypoint : JoinedOrSeparate<["-", "/"], "E">, Flags<[CoreOption, RewriteOption]>, Group<hlslcomp_Group>,
|
|
||||||
HelpText<"Entry point name">;
|
|
||||||
// /I <include> - already defined above
|
|
||||||
def _vi : Flag<["-", "/"], "Vi">, Alias<H>, Flags<[CoreOption]>, Group<hlslcomp_Group>,
|
|
||||||
HelpText<"Display details about the include process.">;
|
|
||||||
def Od : Flag<["-", "/"], "Od">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
|
|
||||||
HelpText<"Disable optimizations">;
|
|
||||||
def _SLASH_WX : Flag<["-", "/"], "WX">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
|
|
||||||
HelpText<"Treat warnings as errors">;
|
|
||||||
def VD : Flag<["-", "/"], "Vd">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
|
|
||||||
HelpText<"Disable validation">;
|
|
||||||
def _SLASH_Zi : Flag<["-", "/"], "Zi">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
|
|
||||||
HelpText<"Enable debug information. Cannot be used together with -Zs">;
|
|
||||||
def Zs : Flag<["-", "/"], "Zs">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
|
|
||||||
HelpText<"Generate small PDB with just sources and compile options. Cannot be used together with -Zi">;
|
|
||||||
def recompile : Flag<["-", "/"], "recompile">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
|
|
||||||
HelpText<"recompile from DXIL container with Debug Info or Debug Info bitcode file">;
|
|
||||||
def Zpr : Flag<["-", "/"], "Zpr">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
|
|
||||||
HelpText<"Pack matrices in row-major order">;
|
|
||||||
def Zpc : Flag<["-", "/"], "Zpc">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
|
|
||||||
HelpText<"Pack matrices in column-major order">;
|
|
||||||
def Zss : Flag<["-", "/"], "Zss">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
|
|
||||||
HelpText<"Compute Shader Hash considering source information">;
|
|
||||||
def Zsb : Flag<["-", "/"], "Zsb">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
|
|
||||||
HelpText<"Compute Shader Hash considering only output binary">;
|
|
||||||
|
|
||||||
// deprecated /Gpp def Gpp : Flag<["-", "/"], "Gpp">, HelpText<"Force partial precision">;
|
|
||||||
def Gfa : Flag<["-", "/"], "Gfa">, HelpText<"Avoid flow control constructs">, Flags<[CoreOption]>, Group<hlslcomp_Group>;
|
|
||||||
def Gfp : Flag<["-", "/"], "Gfp">, HelpText<"Prefer flow control constructs">, Flags<[CoreOption]>, Group<hlslcomp_Group>;
|
|
||||||
// /Gdp - disable effect performance mode - unsupported
|
|
||||||
def Gec : Flag<["-", "/"], "Gec">, HelpText<"Enable backward compatibility mode">, Flags<[CoreOption]>, Group<hlslcomp_Group>;
|
|
||||||
def Ges : Flag<["-", "/"], "Ges">, HelpText<"Enable strict mode">, Flags<[CoreOption]>, Group<hlslcomp_Group>;
|
|
||||||
def Gis : Flag<["-", "/"], "Gis">, HelpText<"Force IEEE strictness">, Flags<[CoreOption]>, Group<hlslcomp_Group>;
|
|
||||||
|
|
||||||
def denorm : JoinedOrSeparate<["-", "/"], "denorm">, HelpText<"select denormal value options (any, preserve, ftz). any is the default.">, Flags<[CoreOption]>, Group<hlslcomp_Group>;
|
|
||||||
|
|
||||||
def Fo : JoinedOrSeparate<["-", "/"], "Fo">, MetaVarName<"<file>">, HelpText<"Output object file">, Flags<[CoreOption, RewriteOption, DriverOption]>, Group<hlslcomp_Group>;
|
|
||||||
// def Fl : JoinedOrSeparate<["-", "/"], "Fl">, MetaVarName<"<file>">, HelpText<"Output a library">;
|
|
||||||
def Fc : JoinedOrSeparate<["-", "/"], "Fc">, MetaVarName<"<file>">, HelpText<"Output assembly code listing file">, Flags<[DriverOption]>, Group<hlslcomp_Group>;
|
|
||||||
//def Fx : JoinedOrSeparate<["-", "/"], "Fx">, MetaVarName<"<file>">, HelpText<"Output assembly code and hex listing file">;
|
|
||||||
def Fh : JoinedOrSeparate<["-", "/"], "Fh">, MetaVarName<"<file>">, HelpText<"Output header file containing object code">, Flags<[DriverOption]>, Group<hlslcomp_Group>;
|
|
||||||
def Fe : JoinedOrSeparate<["-", "/"], "Fe">, MetaVarName<"<file>">, HelpText<"Output warnings and errors to the given file">, Flags<[CoreOption, DriverOption]>, Group<hlslcomp_Group>;
|
|
||||||
def Fd : JoinedOrSeparate<["-", "/"], "Fd">, MetaVarName<"<file>">,
|
|
||||||
HelpText<"Write debug information to the given file, or automatically named file in directory when ending in '\\'">,
|
|
||||||
Flags<[CoreOption, DriverOption]>, Group<hlslcomp_Group>;
|
|
||||||
def Fre : Separate<["-", "/"], "Fre">, MetaVarName<"<file>">, HelpText<"Output reflection to the given file">, Flags<[CoreOption, DriverOption]>, Group<hlslcomp_Group>;
|
|
||||||
def Frs : Separate<["-", "/"], "Frs">, MetaVarName<"<file>">, HelpText<"Output root signature to the given file">, Flags<[CoreOption, DriverOption]>, Group<hlslcomp_Group>;
|
|
||||||
def Fsh : Separate<["-", "/"], "Fsh">, MetaVarName<"<file>">, HelpText<"Output shader hash to the given file">, Flags<[CoreOption, DriverOption]>, Group<hlslcomp_Group>;
|
|
||||||
def Fi : JoinedOrSeparate<["-", "/"], "Fi">, MetaVarName<"<file>">,
|
|
||||||
HelpText<"Set preprocess output file name (with /P)">,
|
|
||||||
Flags<[CoreOption, DriverOption]>, Group<hlslcomp_Group>;
|
|
||||||
|
|
||||||
def Vn : JoinedOrSeparate<["-", "/"], "Vn">, MetaVarName<"<name>">, HelpText<"Use <name> as variable name in header file">, Flags<[DriverOption]>, Group<hlslcomp_Group>;
|
|
||||||
def Cc : Flag<["-", "/"], "Cc">, HelpText<"Output color coded assembly listings">, Group<hlslcomp_Group>, Flags<[DriverOption]>;
|
|
||||||
def Ni : Flag<["-", "/"], "Ni">, HelpText<"Output instruction numbers in assembly listings">, Group<hlslcomp_Group>, Flags<[DriverOption]>;
|
|
||||||
def No : Flag<["-", "/"], "No">, HelpText<"Output instruction byte offsets in assembly listings">, Group<hlslcomp_Group>, Flags<[DriverOption]>;
|
|
||||||
def Lx : Flag<["-", "/"], "Lx">, HelpText<"Output hexadecimal literals">, Group<hlslcomp_Group>, Flags<[DriverOption]>;
|
|
||||||
|
|
||||||
// In place of 'E' for clang; fxc uses 'E' for entry point.
|
|
||||||
def P : Flag<["-", "/"], "P">, Flags<[CoreOption, DriverOption]>, Group<hlslutil_Group>,
|
|
||||||
HelpText<"Preprocess to file">;
|
|
||||||
def Po : Flag<["-", "/"], "Po">, Flags<[CoreOption, DriverOption]>, Group<hlslutil_Group>,
|
|
||||||
HelpText<"Preprocess to file (deprecated, use /P /Fi instead)">;
|
|
||||||
|
|
||||||
// @<file> - options response file
|
|
||||||
|
|
||||||
def dumpbin : Flag<["-", "/"], "dumpbin">, Flags<[DriverOption]>, Group<hlslutil_Group>,
|
|
||||||
HelpText<"Load a binary file rather than compiling">;
|
|
||||||
def link : Flag<["-", "/"], "link">, Flags<[DriverOption]>, Group<hlslutil_Group>,
|
|
||||||
HelpText<"Link list of libraries provided in <inputs> argument separated by ';'">;
|
|
||||||
def Qstrip_reflect : Flag<["-", "/"], "Qstrip_reflect">, Flags<[CoreOption, DriverOption]>, Group<hlslutil_Group>,
|
|
||||||
HelpText<"Strip reflection data from shader bytecode (must be used with /Fo <file>)">;
|
|
||||||
def Qstrip_debug : Flag<["-", "/"], "Qstrip_debug">, Flags<[CoreOption, DriverOption]>, Group<hlslutil_Group>,
|
|
||||||
HelpText<"Strip debug information from 4_0+ shader bytecode (must be used with /Fo <file>)">;
|
|
||||||
def Qembed_debug : Flag<["-", "/"], "Qembed_debug">, Flags<[CoreOption]>, Group<hlslutil_Group>,
|
|
||||||
HelpText<"Embed PDB in shader container (must be used with /Zi)">;
|
|
||||||
def Qstrip_priv : Flag<["-", "/"], "Qstrip_priv">, Flags<[CoreOption, DriverOption]>, Group<hlslutil_Group>,
|
|
||||||
HelpText<"Strip private data from shader bytecode (must be used with /Fo <file>)">;
|
|
||||||
def Qsource_in_debug_module : Flag<["-", "/"], "Qsource_in_debug_module">, Flags<[CoreOption]>, Group<hlslutil_Group>,
|
|
||||||
HelpText<"Embed source code in PDB">;
|
|
||||||
def Qpdb_in_private : Flag<["-", "/"], "Qpdb_in_private">, Flags<[CoreOption, HelpHidden]>, Group<hlslutil_Group>,
|
|
||||||
HelpText<"Store PDB in private user data.">;
|
|
||||||
|
|
||||||
def Qstrip_rootsignature : Flag<["-", "/"], "Qstrip_rootsignature">, Flags<[CoreOption, DriverOption]>, Group<hlslutil_Group>, HelpText<"Strip root signature data from shader bytecode (must be used with /Fo <file>)">;
|
|
||||||
def setrootsignature : JoinedOrSeparate<["-", "/"], "setrootsignature">, MetaVarName<"<file>">, Flags<[CoreOption, DriverOption]>, Group<hlslutil_Group>, HelpText<"Attach root signature to shader bytecode">;
|
|
||||||
def extractrootsignature : Flag<["-", "/"], "extractrootsignature">, Flags<[DriverOption]>, Group<hlslutil_Group>, HelpText<"Extract root signature from shader bytecode (must be used with /Fo <file>)">;
|
|
||||||
def verifyrootsignature : JoinedOrSeparate<["-", "/"], "verifyrootsignature">, MetaVarName<"<file>">, Flags<[DriverOption]>, Group<hlslutil_Group>, HelpText<"Verify shader bytecode with root signature">;
|
|
||||||
def force_rootsig_ver : JoinedOrSeparate<["-", "/"], "force-rootsig-ver">, Flags<[CoreOption]>, MetaVarName<"<profile>">, Group<hlslcomp_Group>, HelpText<"force root signature version (rootsig_1_1 if omitted)">;
|
|
||||||
def force_rootsig_ver_ : JoinedOrSeparate<["-", "/"], "force_rootsig_ver">, Flags<[CoreOption, HelpHidden]>, MetaVarName<"<profile>">, Group<hlslcomp_Group>, HelpText<"force root signature version (rootsig_1_1 if omitted)">;
|
|
||||||
|
|
||||||
// Temporary TEST options, until reflection inside DXIL part can always be stripped
|
|
||||||
def Qkeep_reflect_in_dxil : Flag<["-", "/"], "Qkeep_reflect_in_dxil">,
|
|
||||||
Flags<[CoreOption, HelpHidden]>, Group<hlslutil_Group>,
|
|
||||||
HelpText<"Keep reflection data in shader bytecode">;
|
|
||||||
def Qstrip_reflect_from_dxil : Flag<["-", "/"], "Qstrip_reflect_from_dxil">,
|
|
||||||
Flags<[CoreOption, HelpHidden]>, Group<hlslutil_Group>,
|
|
||||||
HelpText<"Strip reflection data from shader bytecode (must be used with /Fo <file>)">;
|
|
||||||
|
|
||||||
/*
|
|
||||||
def shtemplate : JoinedOrSeparate<["-", "/"], "shtemplate">, MetaVarName<"<file>">, Group<hlslcomp_Group>,
|
|
||||||
HelpText<"Template shader file for merging/matching resources">;
|
|
||||||
def mergeUAVs : JoinedOrSeparate<["-", "/"], "mergeUAVs">, MetaVarName<"<file>">, Group<hlslcomp_Group>,
|
|
||||||
HelpText<"Merge UAV slots of template shader and current shader">;
|
|
||||||
def matchUAVs : JoinedOrSeparate<["-", "/"], "matchUAVs">, MetaVarName<"<file>">, Group<hlslcomp_Group>,
|
|
||||||
HelpText<"Match template shader UAV slots in current shader">;
|
|
||||||
def enable_unbounded_descriptor_tables : Flag<["-", "/"], "enable_unbounded_descriptor_tables">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
|
|
||||||
HelpText<"Enables unbounded descriptor tables">;
|
|
||||||
*/
|
|
||||||
def res_may_alias : Flag<["-", "/"], "res-may-alias">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
|
|
||||||
HelpText<"Assume that UAVs/SRVs may alias">;
|
|
||||||
def res_may_alias_ : Flag<["-", "/"], "res_may_alias">, Flags<[CoreOption, HelpHidden]>, Group<hlslcomp_Group>,
|
|
||||||
HelpText<"Assume that UAVs/SRVs may alias">;
|
|
||||||
def all_resources_bound : Flag<["-", "/"], "all-resources-bound">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
|
|
||||||
HelpText<"Enables aggressive flattening">;
|
|
||||||
def all_resources_bound_ : Flag<["-", "/"], "all_resources_bound">, Flags<[CoreOption, HelpHidden]>, Group<hlslcomp_Group>,
|
|
||||||
HelpText<"Enables aggressive flattening">;
|
|
||||||
|
|
||||||
def setprivate : JoinedOrSeparate<["-", "/"], "setprivate">, Flags<[CoreOption, DriverOption]>, MetaVarName<"<file>">, Group<hlslutil_Group>,
|
|
||||||
HelpText<"Private data to add to compiled shader blob">;
|
|
||||||
def getprivate : JoinedOrSeparate<["-", "/"], "getprivate">, Flags<[DriverOption]>, MetaVarName<"<file>">, Group<hlslutil_Group>,
|
|
||||||
HelpText<"Save private data from shader blob">;
|
|
||||||
|
|
||||||
def nologo : Flag<["-", "/"], "nologo">, Group<hlslcore_Group>, Flags<[DriverOption, HelpHidden]>,
|
|
||||||
HelpText<"Suppress copyright message">;
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////////
|
|
||||||
// Rewriter Options
|
|
||||||
|
|
||||||
def rw_unchanged : Flag<["-", "/"], "unchanged">, Group<hlslrewrite_Group>, Flags<[RewriteOption]>,
|
|
||||||
HelpText<"Rewrite HLSL, without changes.">;
|
|
||||||
def rw_skip_function_body : Flag<["-", "/"], "skip-fn-body">, Group<hlslrewrite_Group>, Flags<[RewriteOption]>,
|
|
||||||
HelpText<"Translate function definitions to declarations">;
|
|
||||||
def rw_skip_static : Flag<["-", "/"], "skip-static">, Group<hlslrewrite_Group>, Flags<[RewriteOption]>,
|
|
||||||
HelpText<"Remove static functions and globals when used with -skip-fn-body">;
|
|
||||||
def rw_global_extern_by_default : Flag<["-", "/"], "global-extern-by-default">, Group<hlslrewrite_Group>, Flags<[RewriteOption]>,
|
|
||||||
HelpText<"Set extern on non-static globals">;
|
|
||||||
def rw_keep_user_macro : Flag<["-", "/"], "keep-user-macro">, Group<hlslrewrite_Group>, Flags<[RewriteOption]>,
|
|
||||||
HelpText<"Write out user defines after rewritten HLSL">;
|
|
||||||
def rw_extract_entry_uniforms : Flag<["-", "/"], "extract-entry-uniforms">, Group<hlslrewrite_Group>, Flags<[RewriteOption]>,
|
|
||||||
HelpText<"Move uniform parameters from entry point to global scope">;
|
|
||||||
def rw_remove_unused_globals : Flag<["-", "/"], "remove-unused-globals">, Group<hlslrewrite_Group>, Flags<[RewriteOption]>,
|
|
||||||
HelpText<"Remove unused static globals and functions">;
|
|
||||||
def rw_remove_unused_functions : Flag<["-", "/"], "remove-unused-functions">, Group<hlslrewrite_Group>, Flags<[RewriteOption]>,
|
|
||||||
HelpText<"Remove unused functions and types">;
|
|
||||||
def rw_line_directive : Flag<["-", "/"], "line-directive">, Group<hlslrewrite_Group>, Flags<[RewriteOption]>,
|
|
||||||
HelpText<"Add line directive">;
|
|
||||||
def rw_decl_global_cb : Flag<["-", "/"], "decl-global-cb">, Group<hlslrewrite_Group>, Flags<[RewriteOption]>,
|
|
||||||
HelpText<"Collect all global constants outside cbuffer declarations into cbuffer GlobalCB { ... }. Still experimental, not all dependency scenarios handled.">;
|
|
||||||
// Also removed: compress, decompress, /Gch (child effect), /Gpp (partial precision)
|
|
||||||
// /Op - no support for preshaders.
|
|
||||||
Loading…
Reference in New Issue