Proper error reporting: macro backtraces, include chains, clang/msvc output
Diagnostics now match dxc's layout on the cases compared (nested macros,
include chains, #line, bracket matching, missing ';', fatal errors), with
range underlines and fix-it hints on top.
Locations:
- Macro-expanded tokens get clang-style macro locations: an expansion
record (spelling, expansion point, macro name, argument or body).
Errors print at the expansion site with "expanded from macro" notes,
outermost first; argument tokens report at their own position.
- Files remember the #include that entered them ("In file included from").
- #line remapping moved into the source manager so diagnostics use
presumed locations.
- UTF-16 sources with a BOM are decoded, as dxc does.
Engine (src/diag.zig):
- Diagnostics carry a range, notes, fix-it text and a warning group.
- Rendered in source order: the preprocessor runs ahead of the parser, so
diagnostics are sorted by token position; a fatal error hides only what
follows it.
- -fdiagnostics-format=clang|msvc|vi, colors when stderr is a terminal
(-f[no-]color-diagnostics), -WX, -no-warnings, -Wno-<group>,
-ferror-limit=N (default 20, applied in source order).
Messages:
- Missing ';' is reported after the previous token with a ';' fix-it and
context ("at end of declaration", "after expression", ...); parsing
continues when the next token starts a new line.
- Missing ')' / ']' / '}' get "note: to match this '('".
- "expected ';' after struct", "unknown type name 'X'", macro redefinition
with "previous definition is here" [-Wmacro-redefined], #warning
[-W#warnings], carets on the directive name / file name.
- Errors at end of file point just past the last token.
- Empty read()/write() payload qualifiers and static_assert (HLSL 202x)
are rejected, matching dxc under -HV 2021.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
c2481748fb
commit
920a7064a1
399
src/diag.zig
399
src/diag.zig
|
|
@ -1,31 +1,85 @@
|
||||||
//! Diagnostics: collected during compilation and rendered clang-style.
|
//! Diagnostics: collected during compilation, rendered clang-style (or
|
||||||
|
//! 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: source.Loc,
|
loc: 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) };
|
||||||
|
|
@ -35,49 +89,338 @@ pub const Diagnostics = struct {
|
||||||
d.arena.deinit();
|
d.arena.deinit();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn add(d: *Diagnostics, severity: Severity, loc: source.Loc, comptime fmt: []const u8, args: anytype) void {
|
pub fn disableGroup(d: *Diagnostics, group: []const u8) !void {
|
||||||
var sev = severity;
|
const a = d.arena.allocator();
|
||||||
|
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;
|
if (d.suppress_warnings) return null;
|
||||||
if (d.warnings_as_errors) sev = .@"error";
|
if (r.group) |g| if (d.disabled_groups.contains(g)) return null;
|
||||||
|
if (d.warnings_as_errors) {
|
||||||
|
sev = .@"error";
|
||||||
|
promoted = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
const a = d.arena.allocator();
|
const a = d.arena.allocator();
|
||||||
const msg = std.fmt.allocPrint(a, fmt, args) catch "out of memory formatting diagnostic";
|
const diag = a.create(Diagnostic) catch return null;
|
||||||
d.list.append(a, .{ .severity = sev, .loc = loc, .message = msg }) catch return;
|
diag.* = .{
|
||||||
|
.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", .fatal => d.error_count += 1,
|
.@"error" => 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn err(d: *Diagnostics, loc: source.Loc, comptime fmt: []const u8, args: anytype) void {
|
/// Attach a note to `diag` (no-op when the diagnostic was suppressed).
|
||||||
d.add(.@"error", loc, fmt, args);
|
pub fn note(d: *Diagnostics, diag: ?*Diagnostic, loc: Loc, len: u32, comptime fmt: []const u8, args: anytype) void {
|
||||||
|
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 warn(d: *Diagnostics, loc: source.Loc, comptime fmt: []const u8, args: anytype) void {
|
pub fn err(d: *Diagnostics, loc: Loc, comptime fmt: []const u8, args: anytype) void {
|
||||||
d.add(.warning, loc, fmt, args);
|
_ = d.report(.{ .severity = .@"error", .loc = 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Render all diagnostics as `file:line:col: error: message` followed by
|
/// Diagnostics sorted for output (stable by position).
|
||||||
/// the source line and a caret.
|
pub fn sorted(d: *Diagnostics) []const *Diagnostic {
|
||||||
pub fn render(d: *const Diagnostics, sm: *const source.SourceManager, w: *std.Io.Writer) !void {
|
std.sort.insertion(*Diagnostic, d.list.items, {}, struct {
|
||||||
for (d.list.items) |diag| {
|
fn lt(_: void, a: *Diagnostic, b: *Diagnostic) bool {
|
||||||
if (diag.loc.isNone()) {
|
return a.position < b.position;
|
||||||
try w.print("{s}: {s}\n", .{ @tagName(diag.severity), diag.message });
|
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
const f = sm.file(diag.loc.file);
|
}.lt);
|
||||||
const lc = sm.lineCol(diag.loc);
|
return d.list.items;
|
||||||
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);
|
|
||||||
try w.print("{s}\n", .{line});
|
pub fn render(d: *Diagnostics, sm: *const source.SourceManager, w: *std.Io.Writer, style: Style) !void {
|
||||||
for (0..lc.col - 1) |i| try w.writeByte(if (i < line.len and line[i] == '\t') '\t' else ' ');
|
var r: Renderer = .{ .sm = sm, .w = w, .style = style };
|
||||||
try w.writeAll("^\n");
|
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;
|
||||||
|
}
|
||||||
|
levels[n] = e;
|
||||||
|
n += 1;
|
||||||
|
cur = e.expansion;
|
||||||
|
}
|
||||||
|
while (n > 0) {
|
||||||
|
n -= 1;
|
||||||
|
const e = levels[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);
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -80,7 +80,9 @@ 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,
|
||||||
_: u5 = 0,
|
/// Transient, during macro substitution: the token came from an argument.
|
||||||
|
from_arg: bool = false,
|
||||||
|
_: u4 = 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const Token = struct {
|
pub const Token = struct {
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,8 @@ const Allocator = std.mem.Allocator;
|
||||||
const ast = @import("ast.zig");
|
const ast = @import("ast.zig");
|
||||||
const lexer = @import("lexer.zig");
|
const lexer = @import("lexer.zig");
|
||||||
const source = @import("source.zig");
|
const source = @import("source.zig");
|
||||||
const Diagnostics = @import("../diag.zig").Diagnostics;
|
const Diag = @import("../diag.zig");
|
||||||
|
const Diagnostics = Diag.Diagnostics;
|
||||||
const Preprocessor = @import("preproc.zig").Preprocessor;
|
const Preprocessor = @import("preproc.zig").Preprocessor;
|
||||||
const Token = lexer.Token;
|
const Token = lexer.Token;
|
||||||
const Kind = lexer.Kind;
|
const Kind = lexer.Kind;
|
||||||
|
|
@ -42,6 +43,8 @@ pub const Parser = struct {
|
||||||
pub fn fromPreprocessor(arena: Allocator, diags: *Diagnostics, pp: *Preprocessor) !Parser {
|
pub fn fromPreprocessor(arena: Allocator, diags: *Diagnostics, pp: *Preprocessor) !Parser {
|
||||||
var toks: std.ArrayList(Token) = .empty;
|
var toks: std.ArrayList(Token) = .empty;
|
||||||
while (true) {
|
while (true) {
|
||||||
|
// Preprocessor diagnostics are ordered by the token being produced.
|
||||||
|
diags.position = toks.items.len;
|
||||||
const t = try pp.next();
|
const t = try pp.next();
|
||||||
try toks.append(arena, t);
|
try toks.append(arena, t);
|
||||||
if (t.kind == .eof) break;
|
if (t.kind == .eof) break;
|
||||||
|
|
@ -52,7 +55,7 @@ pub const Parser = struct {
|
||||||
pub fn parseTranslationUnit(p: *Parser) Allocator.Error!ast.TranslationUnit {
|
pub fn parseTranslationUnit(p: *Parser) Allocator.Error!ast.TranslationUnit {
|
||||||
try p.pushScope();
|
try p.pushScope();
|
||||||
var decls: std.ArrayList(*ast.Decl) = .empty;
|
var decls: std.ArrayList(*ast.Decl) = .empty;
|
||||||
while (p.tok().kind != .eof) {
|
while (p.tok().kind != .eof and !p.diags.stoppedAt(p.pos)) {
|
||||||
const start = p.pos;
|
const start = p.pos;
|
||||||
p.parseDeclInto(&decls, .global) catch |e| switch (e) {
|
p.parseDeclInto(&decls, .global) catch |e| switch (e) {
|
||||||
error.OutOfMemory => return error.OutOfMemory,
|
error.OutOfMemory => return error.OutOfMemory,
|
||||||
|
|
@ -100,14 +103,81 @@ pub const Parser = struct {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Report an error at the current token (highlighting it).
|
||||||
fn fail(p: *Parser, comptime fmt: []const u8, args: anytype) error{Syntax} {
|
fn fail(p: *Parser, comptime fmt: []const u8, args: anytype) error{Syntax} {
|
||||||
p.diags.err(p.tok().loc, fmt, args);
|
_ = p.reportAt(p.pos, .@"error", fmt, args);
|
||||||
return error.Syntax;
|
return error.Syntax;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn reportAt(p: *Parser, index: usize, sev: Diag.Severity, comptime fmt: []const u8, args: anytype) ?*Diag.Diagnostic {
|
||||||
|
const t = p.toks[index];
|
||||||
|
p.diags.position = index;
|
||||||
|
// At end of input, point just past the last real token (as clang).
|
||||||
|
if (t.kind == .eof and index > 0) {
|
||||||
|
const prev = p.toks[index - 1];
|
||||||
|
const loc = if (prev.loc.isMacro()) prev.loc else prev.loc.advance(@intCast(prev.text.len));
|
||||||
|
return p.diags.report(.{ .severity = sev, .loc = loc }, fmt, args);
|
||||||
|
}
|
||||||
|
const len: u32 = if (t.kind == .eof) 0 else @intCast(t.text.len);
|
||||||
|
return p.diags.report(.{ .severity = sev, .loc = t.loc, .len = len }, fmt, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Location just past the previous token (where a missing `;` goes).
|
||||||
|
fn afterPrevious(p: *const Parser) Loc {
|
||||||
|
if (p.pos == 0) return p.tok().loc;
|
||||||
|
const prev = p.toks[p.pos - 1];
|
||||||
|
if (prev.loc.isMacro()) return prev.loc;
|
||||||
|
return prev.loc.advance(@intCast(prev.text.len));
|
||||||
|
}
|
||||||
|
|
||||||
fn expect(p: *Parser, kind: Kind, what: []const u8) Error!Token {
|
fn expect(p: *Parser, kind: Kind, what: []const u8) Error!Token {
|
||||||
if (p.at(kind)) return p.advance();
|
if (p.at(kind)) return p.advance();
|
||||||
return p.fail("expected {s}, found '{s}'", .{ what, describe(p.tok()) });
|
switch (kind) {
|
||||||
|
.semi => return p.missingSemi(what),
|
||||||
|
.r_paren, .r_square, .r_brace => {
|
||||||
|
const d = p.reportAt(p.pos, .@"error", "expected {s}", .{what});
|
||||||
|
if (p.findOpener(kind)) |i| {
|
||||||
|
const opener = p.toks[i];
|
||||||
|
p.diags.note(d, opener.loc, 1, "to match this '{s}'", .{opener.text});
|
||||||
|
}
|
||||||
|
return error.Syntax;
|
||||||
|
},
|
||||||
|
else => return p.fail("expected {s}, found '{s}'", .{ what, describe(p.tok()) }),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A missing `;` is reported just after the previous token with a
|
||||||
|
/// fix-it. When the next token starts a new line (or closes a block),
|
||||||
|
/// parsing continues as if the `;` were there, avoiding cascades.
|
||||||
|
fn missingSemi(p: *Parser, what: []const u8) Error!Token {
|
||||||
|
p.diags.position = p.pos;
|
||||||
|
_ = p.diags.report(.{ .severity = .@"error", .loc = p.afterPrevious(), .fixit = ";" }, "expected {s}", .{what});
|
||||||
|
const t = p.tok();
|
||||||
|
if (t.flags.bol or t.kind == .r_brace or t.kind == .eof) return .{ .kind = .semi, .text = ";", .loc = t.loc };
|
||||||
|
return error.Syntax;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Index of the unmatched opener for closing token `close`, scanning
|
||||||
|
/// back from the current position.
|
||||||
|
fn findOpener(p: *const Parser, close: Kind) ?usize {
|
||||||
|
const open: Kind = switch (close) {
|
||||||
|
.r_paren => .l_paren,
|
||||||
|
.r_square => .l_square,
|
||||||
|
.r_brace => .l_brace,
|
||||||
|
else => return null,
|
||||||
|
};
|
||||||
|
var depth: u32 = 0;
|
||||||
|
var i = p.pos;
|
||||||
|
while (i > 0) {
|
||||||
|
i -= 1;
|
||||||
|
const k = p.toks[i].kind;
|
||||||
|
if (k == close) depth += 1;
|
||||||
|
if (k == open) {
|
||||||
|
if (depth == 0) return i;
|
||||||
|
depth -= 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn expectIdent(p: *Parser, what: []const u8) Error!Token {
|
fn expectIdent(p: *Parser, what: []const u8) Error!Token {
|
||||||
|
|
@ -404,7 +474,8 @@ pub const Parser = struct {
|
||||||
}
|
}
|
||||||
const name = try p.parseName();
|
const name = try p.parseName();
|
||||||
if (!p.isTypeName(name.last())) {
|
if (!p.isTypeName(name.last())) {
|
||||||
p.diags.err(start.loc, "unknown type name '{s}'", .{name.last()});
|
p.diags.position = p.pos;
|
||||||
|
_ = p.diags.report(.{ .severity = .@"error", .loc = start.loc, .len = @intCast(start.text.len) }, "unknown type name '{s}'", .{name.last()});
|
||||||
return error.Syntax;
|
return error.Syntax;
|
||||||
}
|
}
|
||||||
var args: []const ast.TemplateArg = &.{};
|
var args: []const ast.TemplateArg = &.{};
|
||||||
|
|
@ -525,6 +596,10 @@ pub const Parser = struct {
|
||||||
}
|
}
|
||||||
try cur.appendSlice(p.arena, a.text);
|
try cur.appendSlice(p.arena, a.text);
|
||||||
}
|
}
|
||||||
|
if (kind == .access and cur.items.len == 0 and values.items.len == 1) {
|
||||||
|
// `read()` needs at least one stage.
|
||||||
|
_ = p.reportAt(p.pos, .@"error", "expected identifier", .{});
|
||||||
|
}
|
||||||
_ = p.advance();
|
_ = p.advance();
|
||||||
try values.append(p.arena, cur.items);
|
try values.append(p.arena, cur.items);
|
||||||
try sems.append(p.arena, .{ .loc = ident.loc, .kind = kind, .values = values.items });
|
try sems.append(p.arena, .{ .loc = ident.loc, .kind = kind, .values = values.items });
|
||||||
|
|
@ -670,7 +745,7 @@ pub const Parser = struct {
|
||||||
if (p.eat(.l_brace)) {
|
if (p.eat(.l_brace)) {
|
||||||
try p.pushScope();
|
try p.pushScope();
|
||||||
var list: std.ArrayList(*ast.Decl) = .empty;
|
var list: std.ArrayList(*ast.Decl) = .empty;
|
||||||
while (!p.at(.r_brace) and !p.at(.eof)) {
|
while (!p.at(.r_brace) and !p.at(.eof) and !p.diags.stoppedAt(p.pos)) {
|
||||||
const before = p.pos;
|
const before = p.pos;
|
||||||
// Access specifiers: `public:`.
|
// Access specifiers: `public:`.
|
||||||
if ((p.atIdent("public") or p.atIdent("private") or p.atIdent("protected")) and p.peek(1).kind == .colon) {
|
if ((p.atIdent("public") or p.atIdent("private") or p.atIdent("protected")) and p.peek(1).kind == .colon) {
|
||||||
|
|
@ -712,11 +787,29 @@ pub const Parser = struct {
|
||||||
|
|
||||||
if (ctx == .typedef) return;
|
if (ctx == .typedef) return;
|
||||||
if (p.eat(.semi)) return;
|
if (p.eat(.semi)) return;
|
||||||
|
if (members != null and p.startsNewDeclAfterStruct()) {
|
||||||
|
// `struct S { ... }` followed by an unrelated declaration on a
|
||||||
|
// new line: the `;` is missing.
|
||||||
|
_ = try p.missingSemi("';' after struct");
|
||||||
|
return;
|
||||||
|
}
|
||||||
// `struct S { ... } a, b;`
|
// `struct S { ... } a, b;`
|
||||||
const ty = try p.mk(ast.TypeRef, .{ .loc = name_loc, .name = try p.simpleName(name_loc, name.?) });
|
const ty = try p.mk(ast.TypeRef, .{ .loc = name_loc, .name = try p.simpleName(name_loc, name.?) });
|
||||||
try p.parseDeclaratorsInto(out, &.{}, quals, &.{}, ty, ctx);
|
try p.parseDeclaratorsInto(out, &.{}, quals, &.{}, ty, ctx);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// After a struct body without `;`: does the next line look like a new
|
||||||
|
/// declaration rather than declarators for the struct?
|
||||||
|
fn startsNewDeclAfterStruct(p: *const Parser) bool {
|
||||||
|
const t = p.tok();
|
||||||
|
if (!t.flags.bol and t.kind != .eof) return false;
|
||||||
|
if (t.kind == .eof or t.kind == .l_square or t.kind == .pragma) return true;
|
||||||
|
if (t.kind != .identifier) return false;
|
||||||
|
if (isReserved(t.text) or qualifierField(t.text) != null) return true;
|
||||||
|
// `Type name` on the next line.
|
||||||
|
return p.peek(1).kind == .identifier or p.peek(1).kind == .colon_colon or p.peek(1).kind == .less;
|
||||||
|
}
|
||||||
|
|
||||||
/// Declare a name in the scope enclosing an open template scope (so a
|
/// Declare a name in the scope enclosing an open template scope (so a
|
||||||
/// template's own name outlives its parameters).
|
/// template's own name outlives its parameters).
|
||||||
fn declareNameOuter(p: *Parser, name: []const u8, kind: NameKind, in_template: bool) Allocator.Error!void {
|
fn declareNameOuter(p: *Parser, name: []const u8, kind: NameKind, in_template: bool) Allocator.Error!void {
|
||||||
|
|
@ -735,7 +828,7 @@ pub const Parser = struct {
|
||||||
const sems = try p.parseSemantics(false, &bitfield);
|
const sems = try p.parseSemantics(false, &bitfield);
|
||||||
_ = try p.expect(.l_brace, "'{'");
|
_ = try p.expect(.l_brace, "'{'");
|
||||||
var members: std.ArrayList(*ast.Decl) = .empty;
|
var members: std.ArrayList(*ast.Decl) = .empty;
|
||||||
while (!p.at(.r_brace) and !p.at(.eof)) {
|
while (!p.at(.r_brace) and !p.at(.eof) and !p.diags.stoppedAt(p.pos)) {
|
||||||
const before = p.pos;
|
const before = p.pos;
|
||||||
p.parseDeclInto(&members, .member) catch |e| switch (e) {
|
p.parseDeclInto(&members, .member) catch |e| switch (e) {
|
||||||
error.OutOfMemory => return error.OutOfMemory,
|
error.OutOfMemory => return error.OutOfMemory,
|
||||||
|
|
@ -799,7 +892,7 @@ pub const Parser = struct {
|
||||||
const name = try p.expectIdent("namespace name");
|
const name = try p.expectIdent("namespace name");
|
||||||
_ = try p.expect(.l_brace, "'{'");
|
_ = try p.expect(.l_brace, "'{'");
|
||||||
var decls: std.ArrayList(*ast.Decl) = .empty;
|
var decls: std.ArrayList(*ast.Decl) = .empty;
|
||||||
while (!p.at(.r_brace) and !p.at(.eof)) {
|
while (!p.at(.r_brace) and !p.at(.eof) and !p.diags.stoppedAt(p.pos)) {
|
||||||
const before = p.pos;
|
const before = p.pos;
|
||||||
p.parseDeclInto(&decls, .global) catch |e| switch (e) {
|
p.parseDeclInto(&decls, .global) catch |e| switch (e) {
|
||||||
error.OutOfMemory => return error.OutOfMemory,
|
error.OutOfMemory => return error.OutOfMemory,
|
||||||
|
|
@ -843,6 +936,8 @@ pub const Parser = struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parseStaticAssert(p: *Parser) Error!*ast.Decl {
|
fn parseStaticAssert(p: *Parser) Error!*ast.Decl {
|
||||||
|
// Parsed for recovery, but not part of HLSL 2021 (dxc rejects it).
|
||||||
|
_ = p.reportAt(p.pos, .@"error", "'static_assert' requires HLSL 202x; zdxc implements HLSL 2021", .{});
|
||||||
const kw = p.advance();
|
const kw = p.advance();
|
||||||
_ = try p.expect(.l_paren, "'('");
|
_ = try p.expect(.l_paren, "'('");
|
||||||
const cond = try p.parseAssign();
|
const cond = try p.parseAssign();
|
||||||
|
|
@ -928,7 +1023,7 @@ pub const Parser = struct {
|
||||||
if (template_params.len > 0 and qualified_var == null) try p.declareNameOuter(name.text, .template_func, true);
|
if (template_params.len > 0 and qualified_var == null) try p.declareNameOuter(name.text, .template_func, true);
|
||||||
if (!p.eat(.comma)) break;
|
if (!p.eat(.comma)) break;
|
||||||
}
|
}
|
||||||
_ = try p.expect(.semi, "';'");
|
_ = try p.expect(.semi, "';' at end of declaration");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Skip a balanced `open ... close` group (legacy annotations and state
|
/// Skip a balanced `open ... close` group (legacy annotations and state
|
||||||
|
|
@ -1063,7 +1158,7 @@ pub const Parser = struct {
|
||||||
try p.pushScope();
|
try p.pushScope();
|
||||||
defer p.popScope();
|
defer p.popScope();
|
||||||
var stmts: std.ArrayList(*ast.Stmt) = .empty;
|
var stmts: std.ArrayList(*ast.Stmt) = .empty;
|
||||||
while (!p.at(.r_brace) and !p.at(.eof)) {
|
while (!p.at(.r_brace) and !p.at(.eof) and !p.diags.stoppedAt(p.pos)) {
|
||||||
const before = p.pos;
|
const before = p.pos;
|
||||||
const s = p.parseStmt() catch |e| switch (e) {
|
const s = p.parseStmt() catch |e| switch (e) {
|
||||||
error.OutOfMemory => return error.OutOfMemory,
|
error.OutOfMemory => return error.OutOfMemory,
|
||||||
|
|
@ -1145,7 +1240,7 @@ pub const Parser = struct {
|
||||||
_ = try p.expect(.l_paren, "'('");
|
_ = try p.expect(.l_paren, "'('");
|
||||||
const cond = try p.parseExpr();
|
const cond = try p.parseExpr();
|
||||||
_ = try p.expect(.r_paren, "')'");
|
_ = try p.expect(.r_paren, "')'");
|
||||||
_ = try p.expect(.semi, "';'");
|
_ = try p.expect(.semi, "';' after do/while statement");
|
||||||
return p.mkStmt(t.loc, attrs, .{ .do_while = .{ .body = body, .cond = cond } });
|
return p.mkStmt(t.loc, attrs, .{ .do_while = .{ .body = body, .cond = cond } });
|
||||||
}
|
}
|
||||||
if (std.mem.eql(u8, w, "switch")) {
|
if (std.mem.eql(u8, w, "switch")) {
|
||||||
|
|
@ -1170,7 +1265,7 @@ pub const Parser = struct {
|
||||||
}
|
}
|
||||||
if (std.mem.eql(u8, w, "break") or std.mem.eql(u8, w, "continue") or std.mem.eql(u8, w, "discard")) {
|
if (std.mem.eql(u8, w, "break") or std.mem.eql(u8, w, "continue") or std.mem.eql(u8, w, "discard")) {
|
||||||
_ = p.advance();
|
_ = p.advance();
|
||||||
_ = try p.expect(.semi, "';'");
|
_ = try p.expect(.semi, if (w[0] == 'b') "';' after break statement" else if (w[0] == 'c') "';' after continue statement" else "';' after discard statement");
|
||||||
const kind: ast.Stmt.Kind = if (w[0] == 'b') .@"break" else if (w[0] == 'c') .@"continue" else .discard;
|
const kind: ast.Stmt.Kind = if (w[0] == 'b') .@"break" else if (w[0] == 'c') .@"continue" else .discard;
|
||||||
return p.mkStmt(t.loc, attrs, kind);
|
return p.mkStmt(t.loc, attrs, kind);
|
||||||
}
|
}
|
||||||
|
|
@ -1178,7 +1273,7 @@ pub const Parser = struct {
|
||||||
_ = p.advance();
|
_ = p.advance();
|
||||||
var value: ?*ast.Expr = null;
|
var value: ?*ast.Expr = null;
|
||||||
if (!p.at(.semi)) value = if (p.at(.l_brace)) try p.parseInitializer() else try p.parseExpr();
|
if (!p.at(.semi)) value = if (p.at(.l_brace)) try p.parseInitializer() else try p.parseExpr();
|
||||||
_ = try p.expect(.semi, "';'");
|
_ = try p.expect(.semi, "';' after return statement");
|
||||||
return p.mkStmt(t.loc, attrs, .{ .@"return" = value });
|
return p.mkStmt(t.loc, attrs, .{ .@"return" = value });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1221,13 +1316,23 @@ pub const Parser = struct {
|
||||||
fn parseSimpleStmt(p: *Parser, in_for: bool) Error!*ast.Stmt {
|
fn parseSimpleStmt(p: *Parser, in_for: bool) Error!*ast.Stmt {
|
||||||
_ = in_for;
|
_ = in_for;
|
||||||
const t = p.tok();
|
const t = p.tok();
|
||||||
|
// `Unknown x;`: two identifiers in a row where the first is not a
|
||||||
|
// known name. Report it once and treat it as a type from here on.
|
||||||
|
if (t.kind == .identifier and !isReserved(t.text) and p.lookupName(t.text) == null and !isBuiltinType(t.text)) {
|
||||||
|
const n1 = p.peek(1);
|
||||||
|
const n2 = p.peek(2).kind;
|
||||||
|
if (n1.kind == .identifier and !isReserved(n1.text) and (n2 == .semi or n2 == .equal or n2 == .comma or n2 == .l_square or n2 == .colon)) {
|
||||||
|
_ = p.reportAt(p.pos, .@"error", "unknown type name '{s}'", .{t.text});
|
||||||
|
try p.declareName(t.text, .type);
|
||||||
|
}
|
||||||
|
}
|
||||||
if (p.startsLocalDecl()) {
|
if (p.startsLocalDecl()) {
|
||||||
var decls: std.ArrayList(*ast.Decl) = .empty;
|
var decls: std.ArrayList(*ast.Decl) = .empty;
|
||||||
try p.parseDeclInto(&decls, .local);
|
try p.parseDeclInto(&decls, .local);
|
||||||
return p.mkStmt(t.loc, &.{}, .{ .decl = decls.items });
|
return p.mkStmt(t.loc, &.{}, .{ .decl = decls.items });
|
||||||
}
|
}
|
||||||
const e = try p.parseExpr();
|
const e = try p.parseExpr();
|
||||||
_ = try p.expect(.semi, "';'");
|
_ = try p.expect(.semi, "';' after expression");
|
||||||
return p.mkStmt(t.loc, &.{}, .{ .expr = e });
|
return p.mkStmt(t.loc, &.{}, .{ .expr = e });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1928,3 +2033,55 @@ test "C++-isms found in the corpus" {
|
||||||
\\ (var float2x2 m = (cast float2x2 0))})
|
\\ (var float2x2 m = (cast float2x2 0))})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
test "diagnostics: include chain, macro backtrace, ordering, fix-its" {
|
||||||
|
const gpa = testing.allocator;
|
||||||
|
var t: TestParse = .{};
|
||||||
|
try t.mfs.put(gpa, "./inc.h", "#define SQR(x) ((x) * (x)\nfloat f(float a) { return SQR(a); }\n");
|
||||||
|
defer t.mfs.deinit(gpa);
|
||||||
|
defer t.deinit();
|
||||||
|
_ = try t.run(
|
||||||
|
\\#include "inc.h"
|
||||||
|
\\#define FOO 1
|
||||||
|
\\#define FOO 2
|
||||||
|
\\float x = 1.0
|
||||||
|
\\float y = (x + 2;
|
||||||
|
\\#include "missing.h"
|
||||||
|
\\int never = ;
|
||||||
|
);
|
||||||
|
var out: std.Io.Writer.Allocating = .init(gpa);
|
||||||
|
defer out.deinit();
|
||||||
|
try t.diags.render(&t.sm, &out.writer, .{});
|
||||||
|
try testing.expectEqualStrings(
|
||||||
|
\\In file included from t.hlsl:1:
|
||||||
|
\\./inc.h:2:33: error: expected ')'
|
||||||
|
\\float f(float a) { return SQR(a); }
|
||||||
|
\\ ^
|
||||||
|
\\./inc.h:2:27: note: to match this '('
|
||||||
|
\\float f(float a) { return SQR(a); }
|
||||||
|
\\ ^
|
||||||
|
\\./inc.h:1:16: note: expanded from macro 'SQR'
|
||||||
|
\\#define SQR(x) ((x) * (x)
|
||||||
|
\\ ^
|
||||||
|
\\t.hlsl:3:9: warning: 'FOO' macro redefined [-Wmacro-redefined]
|
||||||
|
\\#define FOO 2
|
||||||
|
\\ ^~~
|
||||||
|
\\t.hlsl:2:9: note: previous definition is here
|
||||||
|
\\#define FOO 1
|
||||||
|
\\ ^~~
|
||||||
|
\\t.hlsl:4:14: error: expected ';' at end of declaration
|
||||||
|
\\float x = 1.0
|
||||||
|
\\ ^
|
||||||
|
\\ ;
|
||||||
|
\\t.hlsl:5:17: error: expected ')'
|
||||||
|
\\float y = (x + 2;
|
||||||
|
\\ ^
|
||||||
|
\\t.hlsl:5:11: note: to match this '('
|
||||||
|
\\float y = (x + 2;
|
||||||
|
\\ ^
|
||||||
|
\\t.hlsl:6:10: fatal error: 'missing.h' file not found
|
||||||
|
\\#include "missing.h"
|
||||||
|
\\ ^~~~~~~~~~~
|
||||||
|
\\
|
||||||
|
, out.written());
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@ 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;
|
||||||
|
|
@ -119,16 +120,9 @@ 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 = struct { file: []const u8, line: u32 };
|
pub const PresumedLoc = source.PresumedLoc;
|
||||||
|
|
||||||
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
|
||||||
|
|
@ -152,7 +146,6 @@ 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,
|
||||||
|
|
@ -188,6 +181,11 @@ 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),
|
||||||
|
|
@ -269,6 +267,8 @@ 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];
|
||||||
|
|
@ -358,7 +358,11 @@ 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| {
|
||||||
t.loc = name.loc;
|
// Each expanded token gets a macro location recording where it
|
||||||
|
// 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;
|
||||||
|
|
@ -390,7 +394,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.warn(loc, "#pragma once in main file", .{});
|
_ = pp.diags.report(.{ .severity = .warning, .loc = loc, .group = "pragma-once-outside-header" }, "#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), {});
|
||||||
}
|
}
|
||||||
|
|
@ -537,7 +541,9 @@ 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| {
|
||||||
try out.append(pp.arena, at);
|
var c = at;
|
||||||
|
c.flags.from_arg = true;
|
||||||
|
try out.append(pp.arena, c);
|
||||||
try paste.append(pp.arena, false);
|
try paste.append(pp.arena, false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -559,6 +565,7 @@ 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);
|
||||||
|
|
@ -644,8 +651,7 @@ pub const Preprocessor = struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn presumedLoc(pp: *const Preprocessor, loc: Loc) PresumedLoc {
|
pub fn presumedLoc(pp: *const Preprocessor, loc: Loc) PresumedLoc {
|
||||||
if (loc.isNone()) return .{ .file = "<unknown>", .line = 0 };
|
return pp.sm.presumedLoc(loc);
|
||||||
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
|
||||||
|
|
@ -657,28 +663,16 @@ pub const Preprocessor = struct {
|
||||||
line_index: u32 = 0,
|
line_index: u32 = 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn presumedLocCursor(pp: *const Preprocessor, loc: Loc, cursor: *LineCursor) PresumedLoc {
|
pub fn presumedLocCursor(pp: *const Preprocessor, loc_in: Loc, cursor: *LineCursor) PresumedLoc {
|
||||||
if (loc.isNone()) return .{ .file = "<unknown>", .line = 0 };
|
if (loc_in.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.applyLineOverrides(loc.file, cursor.line_index + 1);
|
return pp.sm.presumedLine(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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------
|
// ---------------------------------------------------------------------
|
||||||
|
|
@ -740,7 +734,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 = hash.loc });
|
try pp.conds.append(pp.arena, .{ .taken = v, .seen_else = false, .loc = name.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();
|
||||||
|
|
@ -749,7 +743,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 = hash.loc });
|
try pp.conds.append(pp.arena, .{ .taken = v, .seen_else = false, .loc = name.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.
|
||||||
|
|
@ -771,9 +765,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(hash.loc, "{s}", .{lx.restOfLine()});
|
pp.diags.err(name.loc, "{s}", .{lx.restOfLine()});
|
||||||
} else if (std.mem.eql(u8, d, "warning")) {
|
} else if (std.mem.eql(u8, d, "warning")) {
|
||||||
pp.diags.warn(hash.loc, "{s}", .{lx.restOfLine()});
|
_ = pp.diags.report(.{ .severity = .warning, .loc = name.loc, .group = "#warnings" }, "{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 {
|
||||||
|
|
@ -939,10 +933,12 @@ 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.warn(name.loc, "redefining builtin macro", .{});
|
_ = pp.diags.report(.{ .severity = .warning, .loc = name.loc, .len = len, .group = "builtin-macro-redefined" }, "redefining builtin macro", .{});
|
||||||
} else if (!old.sameDefinition(m)) {
|
} else if (!old.sameDefinition(m)) {
|
||||||
pp.diags.warn(name.loc, "'{s}' macro redefined", .{name.text});
|
const d = pp.diags.report(.{ .severity = .warning, .loc = name.loc, .len = len, .group = "macro-redefined" }, "'{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);
|
||||||
|
|
@ -952,13 +948,23 @@ 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) {
|
||||||
|
|
@ -981,10 +987,11 @@ 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.add(.fatal, directive.loc, "'{s}' file not found with <angled> include; use \"quotes\" instead", .{spelled});
|
_ = pp.diags.report(r, "'{s}' file not found with <angled> include; use \"quotes\" instead", .{spelled});
|
||||||
} else {
|
} else {
|
||||||
pp.diags.add(.fatal, directive.loc, "'{s}' file not found", .{spelled});
|
_ = pp.diags.report(r, "'{s}' file not found", .{spelled});
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
|
@ -994,7 +1001,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.enterFileId(id);
|
try pp.enterFileFrom(id, name_loc);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Search order (matching dxc):
|
/// Search order (matching dxc):
|
||||||
|
|
@ -1117,9 +1124,7 @@ 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;
|
||||||
const gop = try pp.line_overrides.getOrPut(pp.arena, file);
|
try pp.sm.addLineOverride(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,16 +6,44 @@ 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.
|
/// Byte offset into the file's (line-spliced) text, or an expansion
|
||||||
|
/// 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
|
||||||
|
|
@ -88,16 +116,31 @@ 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 };
|
||||||
|
|
@ -145,7 +188,8 @@ 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 no_bom = if (std.mem.startsWith(u8, raw, "\xEF\xBB\xBF")) raw[3..] else raw;
|
const utf8 = try decodeUtf16(a, raw) orelse 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);
|
||||||
|
|
@ -171,8 +215,69 @@ pub const SourceManager = struct {
|
||||||
return &sm.files.items[id];
|
return &sm.files.items[id];
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 1-based line and column.
|
pub fn addLineOverride(sm: *SourceManager, id: FileId, ov: LineOverride) !void {
|
||||||
pub fn lineCol(sm: *const SourceManager, loc: Loc) LineCol {
|
const a = sm.allocator();
|
||||||
|
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 {
|
||||||
|
|
@ -184,7 +289,8 @@ 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: Loc) []const u8 {
|
pub fn lineText(sm: *const SourceManager, loc_in: 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];
|
||||||
|
|
@ -194,6 +300,22 @@ 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;
|
||||||
|
|
@ -244,6 +366,16 @@ 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());
|
||||||
|
|
|
||||||
36
src/main.zig
36
src/main.zig
|
|
@ -21,6 +21,14 @@ const usage =
|
||||||
\\ -Fi <file> Output file for -P
|
\\ -Fi <file> Output file for -P
|
||||||
\\ -HV 2021 HLSL version (only 2021 is supported)
|
\\ -HV 2021 HLSL version (only 2021 is supported)
|
||||||
\\ -enable-16bit-types Enable 16-bit types
|
\\ -enable-16bit-types Enable 16-bit types
|
||||||
|
\\ -WX Treat warnings as errors
|
||||||
|
\\ -no-warnings Suppress warnings
|
||||||
|
\\ -Wno-<group> Disable a warning group (e.g. -Wno-macro-redefined)
|
||||||
|
\\ -fdiagnostics-format=<clang|msvc|vi>
|
||||||
|
\\ Diagnostic location style (msvc: file(line,col))
|
||||||
|
\\ -fcolor-diagnostics, -fno-color-diagnostics
|
||||||
|
\\ Force colors on or off (default: on for terminals)
|
||||||
|
\\ -ferror-limit=<n> Stop after n errors (default 20, 0 = no limit)
|
||||||
\\ --version Print version
|
\\ --version Print version
|
||||||
\\
|
\\
|
||||||
\\DEVELOPMENT (temporary, until the frontend lands):
|
\\DEVELOPMENT (temporary, until the frontend lands):
|
||||||
|
|
@ -47,6 +55,12 @@ 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,
|
parse: bool = false,
|
||||||
dump_ast: bool = false,
|
dump_ast: bool = false,
|
||||||
};
|
};
|
||||||
|
|
@ -117,6 +131,21 @@ fn parseArgs(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, std
|
||||||
opts.spirv = true;
|
opts.spirv = true;
|
||||||
} else if (std.mem.eql(u8, a, "-enable-16bit-types")) {
|
} else if (std.mem.eql(u8, a, "-enable-16bit-types")) {
|
||||||
opts.enable_16bit = true;
|
opts.enable_16bit = true;
|
||||||
|
} else if (std.mem.eql(u8, a, "-WX")) {
|
||||||
|
opts.warnings_as_errors = true;
|
||||||
|
} else if (std.mem.eql(u8, a, "-no-warnings")) {
|
||||||
|
opts.no_warnings = true;
|
||||||
|
} else if (std.mem.startsWith(u8, a, "-Wno-")) {
|
||||||
|
try opts.disabled_warnings.append(arena, a["-Wno-".len..]);
|
||||||
|
} else if (std.mem.startsWith(u8, a, "-fdiagnostics-format=")) {
|
||||||
|
const v = a["-fdiagnostics-format=".len..];
|
||||||
|
opts.diag_format = std.meta.stringToEnum(zdxc.diag.Format, v) orelse return cli.fail("unknown diagnostics format '{s}'", .{v});
|
||||||
|
} else if (std.mem.eql(u8, a, "-fcolor-diagnostics")) {
|
||||||
|
opts.color = true;
|
||||||
|
} else if (std.mem.eql(u8, a, "-fno-color-diagnostics")) {
|
||||||
|
opts.color = false;
|
||||||
|
} else if (std.mem.startsWith(u8, a, "-ferror-limit=")) {
|
||||||
|
opts.error_limit = std.fmt.parseInt(u32, a["-ferror-limit=".len..], 10) catch return cli.fail("invalid -ferror-limit value", .{});
|
||||||
} else if (std.mem.eql(u8, a, "-zdxc-empty")) {
|
} else if (std.mem.eql(u8, a, "-zdxc-empty")) {
|
||||||
opts.empty = true;
|
opts.empty = true;
|
||||||
} else if (std.mem.eql(u8, a, "-zdxc-check-hash")) {
|
} else if (std.mem.eql(u8, a, "-zdxc-check-hash")) {
|
||||||
|
|
@ -187,6 +216,10 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
|
||||||
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,
|
||||||
|
|
@ -204,7 +237,8 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
|
||||||
if (opts.dump_ast) try front.ast_dump.dumpUnit(stdout, tu);
|
if (opts.dump_ast) try front.ast_dump.dumpUnit(stdout, tu);
|
||||||
} else try front.pp_print.print(&pp, &out.writer);
|
} else try front.pp_print.print(&pp, &out.writer);
|
||||||
}
|
}
|
||||||
try diags.render(&sm, cli.stderr);
|
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.Fatal;
|
if (diags.hasErrors()) return error.Fatal;
|
||||||
if (opts.pp_output) |path| {
|
if (opts.pp_output) |path| {
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
//! zdxc: an HLSL 2021 compiler targeting DXIL and SPIR-V.
|
//! zdxc: an HLSL 2021 compiler targeting DXIL and SPIR-V.
|
||||||
|
|
||||||
pub const Diagnostics = @import("diag.zig").Diagnostics;
|
pub const diag = @import("diag.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");
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue