From e52cab34d666abe86b2e3b858223f4107d578ba6 Mon Sep 17 00:00:00 2001 From: Peter Li Date: Sat, 31 Oct 2026 00:29:29 -0700 Subject: [PATCH] Preprocessor review fixes: include search order, #if short-circuit, caching - Quoted includes now search the directory of every file on the include stack (innermost first) before -I, and angled includes search only -I and the compiled-in headers, matching dxc. Angled lookups that only a quoted include would find get dxc's "use quotes" diagnostic. - #if evaluation short-circuits &&, || and ?:; division by zero in an unevaluated operand is no longer an error (dxc accepts these). - File contents are read once per path (with negative caching); each inclusion still gets its own FileId so #line state stays per inclusion. - Include-guarded files (#ifndef X / #if !defined(X) wrapping the whole file) are not re-entered once X is defined. 2000 guarded includes: 65 ms -> 2 ms per run (dxc: 3 ms). - Skipped lines are now skipped token by token, so "/*" inside a string in an #if 0 block no longer swallows the #endif. Co-Authored-By: Claude Opus 5.5 --- src/front/lexer.zig | 34 ++++---- src/front/preproc.zig | 182 ++++++++++++++++++++++++++++++++++++++---- src/front/source.zig | 83 ++++++++++++++++--- 3 files changed, 258 insertions(+), 41 deletions(-) diff --git a/src/front/lexer.zig b/src/front/lexer.zig index 1dc03b3..95777fa 100644 --- a/src/front/lexer.zig +++ b/src/front/lexer.zig @@ -212,25 +212,20 @@ pub const Lexer = struct { return .{ .kind = .string, .flags = .{ .space = trivia.space }, .text = l.text[start..l.pos], .loc = .{ .file = l.file, .offset = start } }; } - /// Skip to the start of the next line (used for skipped conditional - /// blocks and after directives). + /// Skip the rest of the current line (used for skipped conditional + /// blocks and after directives). Works token by token so that `/*` or + /// `//` inside string literals is not mistaken for a comment. pub fn skipLine(l: *Lexer) void { - while (l.pos < l.text.len) { - const c = l.text[l.pos]; - if (c == '\n') return; - if (c == '/' and l.peekAt(l.pos + 1) == '*') { - if (std.mem.indexOfPos(u8, l.text, l.pos + 2, "*/")) |end| { - l.pos = @intCast(end + 2); - continue; - } - l.pos = @intCast(l.text.len); + // At the start of a line, its first token is part of this line. + var line_start = l.at_bol; + while (true) { + const saved = l.*; + const t = l.next(); + if (t.kind == .eof or (t.flags.bol and !line_start)) { + l.* = saved; return; } - if (c == '/' and l.peekAt(l.pos + 1) == '/') { - while (l.pos < l.text.len and l.text[l.pos] != '\n') l.pos += 1; - return; - } - l.pos += 1; + line_start = false; } } @@ -353,6 +348,13 @@ test "punctuators and literals" { try expectKinds("# ## #x", &.{ .hash, .hash_hash, .hash, .identifier }); } +test "skipLine ignores comment markers inside strings" { + var l = Lexer.init("x = \"/*\"; y\n#endif\n", 0); + l.skipLine(); + const t = l.next(); + try std.testing.expect(t.kind == .hash and t.flags.bol); +} + test "comments, flags and lines" { var l = Lexer.init("a /* x\n y */ b // c\n c", 0); const a = l.next(); diff --git a/src/front/preproc.zig b/src/front/preproc.zig index 90989bc..cefa49c 100644 --- a/src/front/preproc.zig +++ b/src/front/preproc.zig @@ -159,7 +159,8 @@ pub const Preprocessor = struct { const f = pp.sm.file(id); try pp.includes.append(pp.arena, .{ .lex = .init(f.text, id), - .dir = std.fs.path.dirname(f.path) orelse ".", + // The predefines pseudo-file has no directory to search. + .dir = if (std.mem.eql(u8, f.path, "")) "" else std.fs.path.dirname(f.path) orelse ".", .cond_base = pp.conds.items.len, }); } @@ -857,37 +858,114 @@ pub const Preprocessor = struct { return; } const id = try pp.resolveInclude(spelled, angled) orelse { - pp.diags.add(.fatal, directive.loc, "'{s}' file not found", .{spelled}); + if (angled and try pp.resolveInclude(spelled, false) != null) { + pp.diags.add(.fatal, directive.loc, "'{s}' file not found with include; use \"quotes\" instead", .{spelled}); + } else { + pp.diags.add(.fatal, directive.loc, "'{s}' file not found", .{spelled}); + } return; }; + // Multiple-include optimization: a guarded file whose guard macro is + // defined would contribute nothing, so do not even enter it. + if (includeGuard(pp.sm.file(id).content)) |guard| { + if (pp.macros.contains(guard)) return; + } if (pp.pragma_once.contains(try pp.fileKey(pp.sm.file(id).path))) return; try pp.enterFileId(id); } + /// Search order (matching dxc): + /// - "quoted": the directory of each file on the include stack, innermost + /// first, then each -I directory; + /// - : each -I directory, then the compiled-in HLSL headers. fn resolveInclude(pp: *Preprocessor, spelled: []const u8, angled: bool) Error!?source.FileId { if (std.fs.path.isAbsolute(spelled)) return pp.sm.load(spelled); - const frame = pp.includes.items[pp.includes.items.len - 1]; - const local = try std.fs.path.join(pp.arena, &.{ frame.dir, spelled }); - if (try pp.sm.load(local)) |id| return id; + if (!angled) { + var i = pp.includes.items.len; + while (i > 0) { + i -= 1; + const frame = pp.includes.items[i]; + if (frame.dir.len == 0) continue; // predefines pseudo-file + const p = try std.fs.path.join(pp.arena, &.{ frame.dir, spelled }); + if (try pp.sm.load(p)) |id| return id; + } + } for (pp.opts.include_dirs) |dir| { const p = try std.fs.path.join(pp.arena, &.{ dir, spelled }); if (try pp.sm.load(p)) |id| return id; } - // Like dxc, fall back to the compiled-in HLSL headers for <...>. if (angled) { - var name = try pp.arena.dupe(u8, spelled); + const name = try pp.arena.dupe(u8, spelled); std.mem.replaceScalar(u8, name, '\\', '/'); if (hlsl_headers.find(name)) |text| { - name = try std.mem.concat(pp.arena, u8, &.{ embedded_prefix, name }); - for (pp.sm.files.items, 0..) |f, i| { - if (std.mem.eql(u8, f.path, name)) return @intCast(i); - } - return try pp.sm.addFile(name, text); + return try pp.sm.loadText(try std.mem.concat(pp.arena, u8, &.{ embedded_prefix, name }), text); } } return null; } + /// The macro guarding `content`, if the whole file is wrapped in + /// `#ifndef X` / `#if !defined(X)` ... `#endif` with no `#else`/`#elif` + /// at the top level and nothing outside. Computed once per content. + fn includeGuard(content: *source.Content) ?[]const u8 { + switch (content.guard) { + .none => return null, + .macro => |m| return m, + .unknown => {}, + } + content.guard = .none; + var lx = lexer.Lexer.init(content.text, 0); + const hash = lx.next(); + if (hash.kind != .hash) return null; + const d = lx.next(); + var name: ?Token = null; + if (d.isIdent("ifndef")) { + name = lx.next(); + } else if (d.isIdent("if")) { + if (lx.next().kind != .exclaim) return null; + if (!lx.next().isIdent("defined")) return null; + var t = lx.next(); + if (t.kind == .l_paren) { + name = lx.next(); + t = lx.next(); + if (t.kind != .r_paren) return null; + } else name = t; + } + const macro = name orelse return null; + if (macro.kind != .identifier) return null; + lx.skipLine(); + var depth: u32 = 1; + while (true) { + const t = lx.next(); + if (t.kind == .eof) return null; + if (!(t.kind == .hash and t.flags.bol)) { + lx.skipLine(); + continue; + } + const dir = lx.next(); + if (dir.flags.bol) { + // Null directive: `dir` starts the next line; re-examine it. + lx.pos = dir.loc.offset; + lx.at_bol = true; + continue; + } + if (dir.isIdent("if") or dir.isIdent("ifdef") or dir.isIdent("ifndef")) { + depth += 1; + } else if (dir.isIdent("endif")) { + depth -= 1; + if (depth == 0) { + lx.skipLine(); + if (lx.next().kind != .eof) return null; + content.guard = .{ .macro = macro.text }; + return macro.text; + } + } else if (depth == 1 and (dir.isIdent("else") or dir.isIdent("elif"))) { + return null; + } + lx.skipLine(); + } + } + fn fileKey(pp: *Preprocessor, path: []const u8) Error![]const u8 { return std.fs.path.resolveAlloc(pp.arena, &.{path}); } @@ -1031,6 +1109,10 @@ const Eval = struct { pp: *Preprocessor, toks: []const Token, pos: usize = 0, + /// Nonzero while evaluating an operand whose value is discarded (the + /// right side of a short-circuited && or ||, the unused arm of ?:). + /// Errors such as division by zero are not reported there. + unevaluated: u32 = 0, const EvalError = error{EvalFailed}; @@ -1068,21 +1150,32 @@ const Eval = struct { if (prec < min_prec) break; e.pos += 1; if (op.kind == .question) { - const t = try e.expr(0); + const cond = lhs.v != 0; + const t = try e.operand(0, !cond); const colon = e.peek() orelse return e.fail("expected ':' in preprocessor expression"); if (colon.kind != .colon) return e.fail("expected ':' in preprocessor expression"); e.pos += 1; - const f = try e.expr(1); - lhs = if (lhs.v != 0) t else f; + const f = try e.operand(1, cond); + lhs = if (cond) t else f; lhs.unsigned = t.unsigned or f.unsigned; continue; } - const rhs = try e.expr(prec + 1); + const skip = (op.kind == .amp_amp and lhs.v == 0) or (op.kind == .pipe_pipe and lhs.v != 0); + const rhs = try e.operand(prec + 1, skip); lhs = try e.binary(op, lhs, rhs); } return lhs; } + /// Parse an operand, marking it unevaluated when `skip` is set. + fn operand(e: *Eval, min_prec: u8, skip: bool) EvalError!Value { + if (skip) e.unevaluated += 1; + defer if (skip) { + e.unevaluated -= 1; + }; + return e.expr(min_prec); + } + fn binary(e: *Eval, op: Token, a: Value, b: Value) EvalError!Value { const u = a.unsigned or b.unsigned; const au: u64 = @bitCast(a.v); @@ -1109,6 +1202,7 @@ const Eval = struct { .star => .{ .v = a.v *% b.v, .unsigned = u }, .slash, .percent => blk: { if (b.v == 0) { + if (e.unevaluated != 0) break :blk .{ .v = 0, .unsigned = u }; e.pp.diags.err(op.loc, "division by zero in preprocessor expression", .{}); return error.EvalFailed; } @@ -1307,3 +1401,59 @@ test "errors are diagnosed" { _ = try t.output(); try std.testing.expectEqual(@as(u32, 2), t.diags.error_count); } + +test "#if short-circuits && || ?:" { + try expectPP("#if 0 && (1/0)\na\n#endif\n#if 1 || (1/0)\nb\n#endif\n#if 0 ? 1/0 : 2\nc\n#endif\n#if 1 ? 3 : 1%0\nd\n#endif", "b c d"); + try expectPP("#if defined(N) && (64 / N > 2)\nbad\n#else\nok\n#endif", "ok"); +} + +test "quoted includes search the include stack innermost first, then -I" { + var t: TestPP = .{}; + try t.init(&.{ + .{ "./sub/b.h", "#include \"deeper/e.h\"\n" }, + .{ "./sub/deeper/e.h", "#include \"f.h\"\n#include \"g.h\"\n#include \n" }, + .{ "./sub/f.h", "f_sub" }, + .{ "./f.h", "f_main" }, + .{ "./g.h", "g_main" }, + .{ "inc/g.h", "g_inc" }, + .{ "inc/a.h", "a_inc" }, + .{ "./sub/deeper/a.h", "a_includer" }, + }, "#include \"sub/b.h\"\n", .{ .include_dirs = &.{"inc"} }); + defer t.deinit(); + try std.testing.expectEqualStrings("f_sub g_main a_inc", try t.output()); + try std.testing.expectEqual(@as(u32, 0), t.diags.error_count); +} + +test "angled includes do not search the includer's directory" { + var t: TestPP = .{}; + try t.init(&.{.{ "./a.h", "a" }}, "#include \n", .{}); + defer t.deinit(); + _ = try t.output(); + try std.testing.expectEqual(@as(u32, 1), t.diags.error_count); + try std.testing.expect(std.mem.indexOf(u8, t.diags.list.items[0].message, "use \"quotes\"") != null); +} + +test "include guards are detected and guarded files are not re-entered" { + var t: TestPP = .{}; + try t.init(&.{ + .{ "./g.h", "// header\n#ifndef G_H\n#define G_H\nint g;\n#if 1\n#endif\n#endif // G_H\n" }, + .{ "./d.h", "#if !defined(D_H)\n#define D_H\nint d;\n#endif\n" }, + .{ "./e.h", "#ifndef E_H\n#define E_H\nint e;\n#else\nint again;\n#endif\n" }, + .{ "./o.h", "#ifndef O_H\n#define O_H\n#endif\nint outside;\n" }, + }, "#include \"g.h\"\n#include \"g.h\"\n#include \"d.h\"\n#include \"d.h\"\n#include \"e.h\"\n#include \"e.h\"\n#include \"o.h\"\n#include \"o.h\"\n", .{}); + defer t.deinit(); + try std.testing.expectEqualStrings("int g ; int d ; int e ; int again ; int outside ; int outside ;", try t.output()); + const sm = &t.sm; + var guards: [4]?[]const u8 = undefined; + for ([_][]const u8{ "./g.h", "./d.h", "./e.h", "./o.h" }, 0..) |path, i| { + guards[i] = Preprocessor.includeGuard(sm.cache.get(path).?.?); + } + try std.testing.expectEqualStrings("G_H", guards[0].?); + try std.testing.expectEqualStrings("D_H", guards[1].?); + try std.testing.expect(guards[2] == null); + try std.testing.expect(guards[3] == null); +} + +test "skipped blocks are skipped token by token" { + try expectPP("#if 0\nx = \"/*\";\n#endif\nok", "ok"); +} diff --git a/src/front/source.zig b/src/front/source.zig index 61d9c2b..202eb38 100644 --- a/src/front/source.zig +++ b/src/front/source.zig @@ -65,11 +65,28 @@ pub const DiskFs = struct { } }; -pub const File = struct { - path: []const u8, +/// Text of a source file, shared by every inclusion of it. +pub const Content = struct { text: []const u8, /// Offsets of the first byte of each line. line_starts: []const u32, + /// Include-guard macro, computed lazily by the preprocessor. + guard: Guard = .unknown, + + pub const Guard = union(enum) { + unknown, + none, + macro: []const u8, + }; +}; + +/// One inclusion of a file. Each `#include` gets its own FileId (so that +/// `#line` and other per-inclusion state stay separate) but shares Content. +pub const File = struct { + path: []const u8, + text: []const u8, + line_starts: []const u32, + content: *Content, }; pub const LineCol = struct { line: u32, col: u32 }; @@ -78,6 +95,8 @@ pub const SourceManager = struct { arena: std.heap.ArenaAllocator, files: std.ArrayList(File) = .empty, fs: FileSystem, + /// path -> contents, or null if the path could not be read. + cache: std.StringHashMapUnmanaged(?*Content) = .empty, pub fn init(gpa: Allocator, fs: FileSystem) SourceManager { return .{ .arena = .init(gpa), .fs = fs }; @@ -91,15 +110,39 @@ pub const SourceManager = struct { return sm.arena.allocator(); } - /// Load a file from the file system; null if it cannot be read. + /// Load a file through the cache; null if it cannot be read. Each call + /// returns a new FileId, but the file system is read once per path. pub fn load(sm: *SourceManager, path: []const u8) !?FileId { - const text = sm.fs.read(sm.allocator(), path) orelse return null; - return try sm.addFile(path, text); + const a = sm.allocator(); + const gop = try sm.cache.getOrPut(a, path); + if (!gop.found_existing) { + gop.key_ptr.* = try a.dupe(u8, path); + gop.value_ptr.* = if (sm.fs.read(a, path)) |raw| try sm.makeContent(raw) else null; + } + const content = gop.value_ptr.* orelse return null; + return try sm.addInclusion(path, content); } - /// Register text under `path`. Backslash-newline sequences are removed - /// (translation phase 2), so offsets refer to the spliced text. + /// Register in-memory text under `path`, through the same cache as + /// `load` (used for compiled-in headers). + pub fn loadText(sm: *SourceManager, path: []const u8, raw: []const u8) !FileId { + const a = sm.allocator(); + const gop = try sm.cache.getOrPut(a, path); + if (!gop.found_existing or gop.value_ptr.* == null) { + gop.key_ptr.* = try a.dupe(u8, path); + gop.value_ptr.* = try sm.makeContent(raw); + } + return sm.addInclusion(path, gop.value_ptr.*.?); + } + + /// Register uncached text under `path` (main file text, predefines). pub fn addFile(sm: *SourceManager, path: []const u8, raw: []const u8) !FileId { + return sm.addInclusion(path, try sm.makeContent(raw)); + } + + /// Backslash-newline sequences are removed (translation phase 2), so + /// offsets refer to the spliced text. + fn makeContent(sm: *SourceManager, raw: []const u8) !*Content { const a = sm.allocator(); const no_bom = if (std.mem.startsWith(u8, raw, "\xEF\xBB\xBF")) raw[3..] else raw; const text = try spliceLines(a, no_bom); @@ -108,10 +151,18 @@ pub const SourceManager = struct { for (text, 0..) |c, i| { if (c == '\n') try starts.append(a, @intCast(i + 1)); } + const content = try a.create(Content); + content.* = .{ .text = text, .line_starts = try starts.toOwnedSlice(a) }; + return content; + } + + fn addInclusion(sm: *SourceManager, path: []const u8, content: *Content) !FileId { + const a = sm.allocator(); try sm.files.append(a, .{ .path = try a.dupe(u8, path), - .text = text, - .line_starts = try starts.toOwnedSlice(a), + .text = content.text, + .line_starts = content.line_starts, + .content = content, }); return @intCast(sm.files.items.len - 1); } @@ -179,6 +230,20 @@ test "line and column lookup" { try std.testing.expectEqualStrings("cd", sm.lineText(.{ .file = id, .offset = 3 })); } +test "files are read once per path" { + var mfs: MemoryFs = .{}; + defer mfs.deinit(std.testing.allocator); + try mfs.put(std.testing.allocator, "a.h", "x"); + var sm = SourceManager.init(std.testing.allocator, mfs.fileSystem()); + defer sm.deinit(); + const a = (try sm.load("a.h")).?; + const b = (try sm.load("a.h")).?; + try std.testing.expect(a != b); + try std.testing.expectEqual(sm.file(a).content, sm.file(b).content); + try std.testing.expect(try sm.load("missing.h") == null); + try std.testing.expect(try sm.load("missing.h") == null); +} + test "line splicing" { var mfs: MemoryFs = .{}; var sm = SourceManager.init(std.testing.allocator, mfs.fileSystem());