Preprocessor performance, round 1: benchmark + vector scans
Adds `zig build bench` (bench/pp_bench.zig): lexes / preprocesses / prints a file list in-process, best of N, files served from memory. On the 4764-file, 13.1 MB DXC test corpus (Apple M-series, ReleaseFast, interleaved A/B against the previous commit): lex 13.3 -> 11.2 ms (-16%) pp 49.7 -> 40.1 ms (-19%) print 68.6 -> 53.2 ms (-22%) Kept: - src/front/scan.zig: portable @Vector scans (width from std.simd.suggestVectorLength). Comment bodies are skipped with vector searches; line-start tables are built from per-block newline bitmasks. - An identifier character table for the (short) identifier scans. - A line cursor for -P printing: O(1) per token instead of a binary search. - A 1024-bit filter over macro names so most identifiers skip hashing; the macro table is presized. Tried and dropped (no gain): vector skipping of blank runs (2% slower; gaps between tokens are mostly a single space) and fusing splice detection into the newline scan. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
c9c3c1fddd
commit
226ef16c96
|
|
@ -0,0 +1,112 @@
|
||||||
|
//! Preprocessor benchmark: lexes / preprocesses a set of files in-process
|
||||||
|
//! and reports the best-of-N wall time and throughput.
|
||||||
|
//!
|
||||||
|
//! Usage: pp_bench [-mode lex|pp|print] [-iters N] <file-list.txt>
|
||||||
|
//! The file list has one path per line. File contents are read once and
|
||||||
|
//! served from memory, so disk I/O is excluded from the timings.
|
||||||
|
|
||||||
|
const std = @import("std");
|
||||||
|
const Io = std.Io;
|
||||||
|
const zdxc = @import("zdxc");
|
||||||
|
const front = zdxc.front;
|
||||||
|
|
||||||
|
const Mode = enum { lex, pp, print };
|
||||||
|
|
||||||
|
/// Serves each path from memory after the first read.
|
||||||
|
const CachedFs = struct {
|
||||||
|
io: Io,
|
||||||
|
gpa: std.mem.Allocator,
|
||||||
|
files: std.StringHashMapUnmanaged(?[]const u8) = .empty,
|
||||||
|
|
||||||
|
fn fileSystem(c: *CachedFs) front.source.FileSystem {
|
||||||
|
return .{ .ctx = c, .readFn = readImpl };
|
||||||
|
}
|
||||||
|
|
||||||
|
fn readImpl(ctx: *anyopaque, _: std.mem.Allocator, path: []const u8) ?[]const u8 {
|
||||||
|
const c: *CachedFs = @ptrCast(@alignCast(ctx));
|
||||||
|
const gop = c.files.getOrPut(c.gpa, path) catch return null;
|
||||||
|
if (!gop.found_existing) {
|
||||||
|
gop.key_ptr.* = c.gpa.dupe(u8, path) catch return null;
|
||||||
|
gop.value_ptr.* = Io.Dir.cwd().readFileAlloc(c.io, path, c.gpa, .limited(256 << 20)) catch null;
|
||||||
|
}
|
||||||
|
return gop.value_ptr.*;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
pub fn main(init: std.process.Init) !void {
|
||||||
|
const gpa = init.gpa;
|
||||||
|
const io = init.io;
|
||||||
|
const arena = init.arena.allocator();
|
||||||
|
const args = try init.minimal.args.toSlice(arena);
|
||||||
|
|
||||||
|
var mode: Mode = .pp;
|
||||||
|
var iters: usize = 5;
|
||||||
|
var list_path: ?[]const u8 = null;
|
||||||
|
var i: usize = 1;
|
||||||
|
while (i < args.len) : (i += 1) {
|
||||||
|
if (std.mem.eql(u8, args[i], "-mode")) {
|
||||||
|
i += 1;
|
||||||
|
mode = std.meta.stringToEnum(Mode, args[i]) orelse return error.BadMode;
|
||||||
|
} else if (std.mem.eql(u8, args[i], "-iters")) {
|
||||||
|
i += 1;
|
||||||
|
iters = try std.fmt.parseInt(usize, args[i], 10);
|
||||||
|
} else list_path = args[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
const list = try Io.Dir.cwd().readFileAlloc(io, list_path orelse return error.MissingFileList, arena, .limited(64 << 20));
|
||||||
|
var paths: std.ArrayList([]const u8) = .empty;
|
||||||
|
var it = std.mem.tokenizeScalar(u8, list, '\n');
|
||||||
|
while (it.next()) |p| try paths.append(arena, p);
|
||||||
|
|
||||||
|
var cfs: CachedFs = .{ .io = io, .gpa = gpa };
|
||||||
|
var total_bytes: usize = 0;
|
||||||
|
for (paths.items) |p| {
|
||||||
|
if (CachedFs.readImpl(&cfs, gpa, p)) |text| total_bytes += text.len;
|
||||||
|
}
|
||||||
|
|
||||||
|
var best: u64 = std.math.maxInt(u64);
|
||||||
|
var checksum: u64 = 0;
|
||||||
|
for (0..iters) |_| {
|
||||||
|
const start = Io.Timestamp.now(io, .awake);
|
||||||
|
checksum = 0;
|
||||||
|
for (paths.items) |p| checksum +%= try runOne(gpa, &cfs, p, mode);
|
||||||
|
const ns: u64 = @intCast(start.durationTo(Io.Timestamp.now(io, .awake)).nanoseconds);
|
||||||
|
best = @min(best, ns);
|
||||||
|
}
|
||||||
|
|
||||||
|
var buf: [256]u8 = undefined;
|
||||||
|
var w = Io.File.Writer.init(.stdout(), io, &buf);
|
||||||
|
const mb = @as(f64, @floatFromInt(total_bytes)) / (1024.0 * 1024.0);
|
||||||
|
const secs = @as(f64, @floatFromInt(best)) / 1e9;
|
||||||
|
try w.interface.print("{s}: {d} files, {d:.1} MB, best {d:.2} ms, {d:.0} MB/s (checksum {d})\n", .{
|
||||||
|
@tagName(mode), paths.items.len, mb, secs * 1000.0, mb / secs, checksum,
|
||||||
|
});
|
||||||
|
try w.interface.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn runOne(gpa: std.mem.Allocator, cfs: *CachedFs, path: []const u8, mode: Mode) !u64 {
|
||||||
|
var arena_state: std.heap.ArenaAllocator = .init(gpa);
|
||||||
|
defer arena_state.deinit();
|
||||||
|
const arena = arena_state.allocator();
|
||||||
|
|
||||||
|
if (mode == .lex) {
|
||||||
|
const text = CachedFs.readImpl(cfs, gpa, path) orelse return 0;
|
||||||
|
var lx = front.lexer.Lexer.init(text, 0);
|
||||||
|
var n: u64 = 0;
|
||||||
|
while (lx.next().kind != .eof) n += 1;
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
var sm = front.source.SourceManager.init(arena, cfs.fileSystem());
|
||||||
|
var diags = zdxc.Diagnostics.init(arena);
|
||||||
|
var pp = front.preproc.Preprocessor.init(arena, &sm, &diags, .{});
|
||||||
|
if (!try pp.enterMainFile(path)) return 0;
|
||||||
|
if (mode == .print) {
|
||||||
|
var out: Io.Writer.Allocating = .init(arena);
|
||||||
|
try front.pp_print.print(&pp, &out.writer);
|
||||||
|
return out.written().len;
|
||||||
|
}
|
||||||
|
var n: u64 = 0;
|
||||||
|
while ((try pp.next()).kind != .eof) n += 1;
|
||||||
|
return n;
|
||||||
|
}
|
||||||
13
build.zig
13
build.zig
|
|
@ -47,6 +47,19 @@ pub fn build(b: *std.Build) void {
|
||||||
oracle.has_side_effects = true;
|
oracle.has_side_effects = true;
|
||||||
oracle_step.dependOn(&oracle.step);
|
oracle_step.dependOn(&oracle.step);
|
||||||
|
|
||||||
|
// Benchmarks always build optimized so numbers are comparable.
|
||||||
|
const bench = b.addExecutable(.{
|
||||||
|
.name = "pp_bench",
|
||||||
|
.root_module = b.createModule(.{
|
||||||
|
.root_source_file = b.path("bench/pp_bench.zig"),
|
||||||
|
.target = target,
|
||||||
|
.optimize = .ReleaseFast,
|
||||||
|
.imports = &.{.{ .name = "zdxc", .module = mod }},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const bench_step = b.step("bench", "Build the preprocessor benchmark (zig-out/bin/pp_bench)");
|
||||||
|
bench_step.dependOn(&b.addInstallArtifact(bench, .{}).step);
|
||||||
|
|
||||||
const oracle_pp_step = b.step("oracle-pp", "Compare zdxc -P with dxc -P over the DXC test corpus");
|
const oracle_pp_step = b.step("oracle-pp", "Compare zdxc -P with dxc -P over the DXC test corpus");
|
||||||
const oracle_pp = b.addSystemCommand(&.{ "sh", "test/oracle/pp.sh" });
|
const oracle_pp = b.addSystemCommand(&.{ "sh", "test/oracle/pp.sh" });
|
||||||
oracle_pp.addArtifactArg(exe);
|
oracle_pp.addArtifactArg(exe);
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const source = @import("source.zig");
|
const source = @import("source.zig");
|
||||||
|
const scan = @import("scan.zig");
|
||||||
|
|
||||||
pub const Kind = enum(u8) {
|
pub const Kind = enum(u8) {
|
||||||
eof,
|
eof,
|
||||||
|
|
@ -133,21 +134,14 @@ pub const Lexer = struct {
|
||||||
'/' => {
|
'/' => {
|
||||||
const n = l.peekAt(l.pos + 1);
|
const n = l.peekAt(l.pos + 1);
|
||||||
if (n == '/') {
|
if (n == '/') {
|
||||||
while (l.pos < l.text.len and l.text[l.pos] != '\n') l.pos += 1;
|
l.pos = @intCast(scan.findNewline(l.text, l.pos + 2));
|
||||||
space = true;
|
space = true;
|
||||||
} else if (n == '*') {
|
} else if (n == '*') {
|
||||||
l.pos += 2;
|
|
||||||
// A newline inside a block comment does not start a
|
// A newline inside a block comment does not start a
|
||||||
// new line for directive purposes (the comment is one
|
// new line for directive purposes (the comment is one
|
||||||
// space after translation phase 3).
|
// space after translation phase 3). An unterminated
|
||||||
while (l.pos < l.text.len) : (l.pos += 1) {
|
// comment runs to EOF.
|
||||||
if (l.text[l.pos] == '*' and l.peekAt(l.pos + 1) == '/') {
|
l.pos = @intCast(scan.skipBlockComment(l.text, l.pos + 2));
|
||||||
l.pos += 2;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Unterminated block comment: consume to EOF.
|
|
||||||
}
|
|
||||||
space = true;
|
space = true;
|
||||||
} else break;
|
} else break;
|
||||||
},
|
},
|
||||||
|
|
@ -235,7 +229,7 @@ pub const Lexer = struct {
|
||||||
l.pos += 1;
|
l.pos += 1;
|
||||||
switch (c) {
|
switch (c) {
|
||||||
'a'...'z', 'A'...'Z', '_' => {
|
'a'...'z', 'A'...'Z', '_' => {
|
||||||
while (l.pos < l.text.len and isIdentChar(l.text[l.pos])) l.pos += 1;
|
l.pos = @intCast(scan.skipIdent(l.text, l.pos));
|
||||||
return .identifier;
|
return .identifier;
|
||||||
},
|
},
|
||||||
'0'...'9' => {
|
'0'...'9' => {
|
||||||
|
|
|
||||||
|
|
@ -11,11 +11,13 @@ pub fn print(pp: *Preprocessor, w: *std.Io.Writer) !void {
|
||||||
var cur_line: u32 = 0;
|
var cur_line: u32 = 0;
|
||||||
var prev: ?Token = null;
|
var prev: ?Token = null;
|
||||||
var line_has_tokens = false;
|
var line_has_tokens = false;
|
||||||
|
var cursor: Preprocessor.LineCursor = .{};
|
||||||
while (true) {
|
while (true) {
|
||||||
const t = try pp.next();
|
const t = try pp.next();
|
||||||
if (t.kind == .eof) break;
|
if (t.kind == .eof) break;
|
||||||
const p = pp.presumedLoc(t.loc);
|
const p = pp.presumedLocCursor(t.loc, &cursor);
|
||||||
const same_file = cur_file != null and std.mem.eql(u8, cur_file.?, p.file);
|
// Paths usually share storage, so compare pointers before bytes.
|
||||||
|
const same_file = if (cur_file) |cf| (cf.ptr == p.file.ptr and cf.len == p.file.len) or std.mem.eql(u8, cf, p.file) else false;
|
||||||
if (!same_file) {
|
if (!same_file) {
|
||||||
if (line_has_tokens) try w.writeByte('\n');
|
if (line_has_tokens) try w.writeByte('\n');
|
||||||
try w.print("#line {d} \"", .{p.line});
|
try w.print("#line {d} \"", .{p.line});
|
||||||
|
|
|
||||||
|
|
@ -72,6 +72,29 @@ const Macro = struct {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const MacroFilter = struct {
|
||||||
|
bits: [filter_words]u64 = @splat(0),
|
||||||
|
|
||||||
|
const filter_words = 16; // 1024 bits
|
||||||
|
|
||||||
|
fn slot(name: []const u8) u10 {
|
||||||
|
const first: u32 = name[0];
|
||||||
|
const last: u32 = name[name.len - 1];
|
||||||
|
const len: u32 = @truncate(name.len);
|
||||||
|
return @truncate(first *% 31 +% last *% 7 +% len *% 131);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add(f: *MacroFilter, name: []const u8) void {
|
||||||
|
const s = slot(name);
|
||||||
|
f.bits[s >> 6] |= @as(u64, 1) << @as(u6, @truncate(s));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mayContain(f: *const MacroFilter, name: []const u8) bool {
|
||||||
|
const s = slot(name);
|
||||||
|
return f.bits[s >> 6] & (@as(u64, 1) << @as(u6, @truncate(s))) != 0;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const Context = struct {
|
const Context = struct {
|
||||||
tokens: []const Token,
|
tokens: []const Token,
|
||||||
pos: usize = 0,
|
pos: usize = 0,
|
||||||
|
|
@ -121,6 +144,9 @@ pub const Preprocessor = struct {
|
||||||
diags: *Diagnostics,
|
diags: *Diagnostics,
|
||||||
opts: Options,
|
opts: Options,
|
||||||
macros: std.StringHashMapUnmanaged(*Macro) = .empty,
|
macros: std.StringHashMapUnmanaged(*Macro) = .empty,
|
||||||
|
/// Conservative filter over defined macro names (bits are never
|
||||||
|
/// cleared), letting most identifiers skip the hash lookup.
|
||||||
|
macro_filter: MacroFilter = .{},
|
||||||
contexts: std.ArrayList(Context) = .empty,
|
contexts: std.ArrayList(Context) = .empty,
|
||||||
includes: std.ArrayList(IncludeFrame) = .empty,
|
includes: std.ArrayList(IncludeFrame) = .empty,
|
||||||
conds: std.ArrayList(Cond) = .empty,
|
conds: std.ArrayList(Cond) = .empty,
|
||||||
|
|
@ -182,10 +208,11 @@ pub const Preprocessor = struct {
|
||||||
.{ "__has_attribute", .has_nothing }, .{ "__has_cpp_attribute", .has_nothing },
|
.{ "__has_attribute", .has_nothing }, .{ "__has_cpp_attribute", .has_nothing },
|
||||||
.{ "__has_declspec_attribute", .has_nothing },
|
.{ "__has_declspec_attribute", .has_nothing },
|
||||||
};
|
};
|
||||||
|
try pp.macros.ensureTotalCapacity(pp.arena, 64);
|
||||||
for (builtins) |b| {
|
for (builtins) |b| {
|
||||||
const m = try pp.arena.create(Macro);
|
const m = try pp.arena.create(Macro);
|
||||||
m.* = .{ .name = b[0], .builtin = b[1] };
|
m.* = .{ .name = b[0], .builtin = b[1] };
|
||||||
try pp.macros.put(pp.arena, b[0], m);
|
try pp.defineMacro(b[0], m);
|
||||||
}
|
}
|
||||||
|
|
||||||
var text: std.Io.Writer.Allocating = .init(pp.arena);
|
var text: std.Io.Writer.Allocating = .init(pp.arena);
|
||||||
|
|
@ -223,6 +250,16 @@ pub const Preprocessor = struct {
|
||||||
try pp.enterFileId(id);
|
try pp.enterFileId(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn defineMacro(pp: *Preprocessor, name: []const u8, m: *Macro) Error!void {
|
||||||
|
pp.macro_filter.add(name);
|
||||||
|
try pp.macros.put(pp.arena, name, m);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lookupMacro(pp: *const Preprocessor, name: []const u8) ?*Macro {
|
||||||
|
if (!pp.macro_filter.mayContain(name)) return null;
|
||||||
|
return pp.macros.get(name);
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------
|
// ---------------------------------------------------------------------
|
||||||
// Raw token sources
|
// Raw token sources
|
||||||
|
|
||||||
|
|
@ -283,7 +320,7 @@ pub const Preprocessor = struct {
|
||||||
if (try pp.pragmaOperator(t)) |pragma| return pragma;
|
if (try pp.pragmaOperator(t)) |pragma| return pragma;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const m = pp.macros.get(t.text) orelse return t;
|
const m = pp.lookupMacro(t.text) orelse return t;
|
||||||
if (m.disabled) {
|
if (m.disabled) {
|
||||||
var painted = t;
|
var painted = t;
|
||||||
painted.flags.no_expand = true;
|
painted.flags.no_expand = true;
|
||||||
|
|
@ -411,7 +448,7 @@ pub const Preprocessor = struct {
|
||||||
}
|
}
|
||||||
// Identifiers naming a currently disabled macro stay painted.
|
// Identifiers naming a currently disabled macro stay painted.
|
||||||
if (t.kind == .identifier and !t.flags.no_expand) {
|
if (t.kind == .identifier and !t.flags.no_expand) {
|
||||||
if (pp.macros.get(t.text)) |am| {
|
if (pp.lookupMacro(t.text)) |am| {
|
||||||
if (am.disabled) t.flags.no_expand = true;
|
if (am.disabled) t.flags.no_expand = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -608,9 +645,33 @@ 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 };
|
if (loc.isNone()) return .{ .file = "<unknown>", .line = 0 };
|
||||||
const phys = pp.sm.lineCol(loc).line;
|
return pp.applyLineOverrides(loc.file, pp.sm.lineCol(loc).line);
|
||||||
var result: PresumedLoc = .{ .file = pp.sm.file(loc.file).path, .line = phys };
|
}
|
||||||
if (pp.line_overrides.get(loc.file)) |list| {
|
|
||||||
|
/// Tracks the physical line of the previous lookup so that a stream of
|
||||||
|
/// increasing locations (as when printing) costs O(1) per token instead
|
||||||
|
/// of a binary search.
|
||||||
|
pub const LineCursor = struct {
|
||||||
|
file: source.FileId = Loc.none.file,
|
||||||
|
/// 0-based index into line_starts of the current line.
|
||||||
|
line_index: u32 = 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub fn presumedLocCursor(pp: *const Preprocessor, loc: Loc, cursor: *LineCursor) PresumedLoc {
|
||||||
|
if (loc.isNone()) return .{ .file = "<unknown>", .line = 0 };
|
||||||
|
const starts = pp.sm.file(loc.file).line_starts;
|
||||||
|
if (cursor.file != loc.file or starts[cursor.line_index] > loc.offset) {
|
||||||
|
cursor.* = .{ .file = loc.file, .line_index = pp.sm.lineCol(loc).line - 1 };
|
||||||
|
} else {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
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| {
|
for (list.items) |ov| {
|
||||||
if (ov.phys_line >= phys) break;
|
if (ov.phys_line >= phys) break;
|
||||||
result.line = ov.line + (phys - ov.phys_line - 1);
|
result.line = ov.line + (phys - ov.phys_line - 1);
|
||||||
|
|
@ -884,7 +945,7 @@ pub const Preprocessor = struct {
|
||||||
pp.diags.warn(name.loc, "'{s}' macro redefined", .{name.text});
|
pp.diags.warn(name.loc, "'{s}' macro redefined", .{name.text});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
try pp.macros.put(pp.arena, name.text, m);
|
try pp.defineMacro(name.text, m);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn handleInclude(pp: *Preprocessor, directive: Token) Error!void {
|
fn handleInclude(pp: *Preprocessor, directive: Token) Error!void {
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,126 @@
|
||||||
|
//! Byte-scanning primitives for the lexer and source manager, written with
|
||||||
|
//! portable `@Vector`s (the vector length comes from
|
||||||
|
//! std.simd.suggestVectorLength; no per-platform code).
|
||||||
|
|
||||||
|
const std = @import("std");
|
||||||
|
|
||||||
|
const vec_len = std.simd.suggestVectorLength(u8) orelse 16;
|
||||||
|
const V = @Vector(vec_len, u8);
|
||||||
|
const Mask = @Int(.unsigned, vec_len);
|
||||||
|
|
||||||
|
inline fn load(text: []const u8, i: usize) V {
|
||||||
|
return text[i..][0..vec_len].*;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline fn bits(m: @Vector(vec_len, bool)) Mask {
|
||||||
|
return @bitCast(m);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Index of the first byte at or after `start` that is not ' ' or '\t',
|
||||||
|
/// or text.len.
|
||||||
|
pub fn skipBlanks(text: []const u8, start: usize) usize {
|
||||||
|
var i = start;
|
||||||
|
while (i + vec_len <= text.len) : (i += vec_len) {
|
||||||
|
const b = load(text, i);
|
||||||
|
const blank = bits(b == @as(V, @splat(' '))) | bits(b == @as(V, @splat('\t')));
|
||||||
|
if (blank != std.math.maxInt(Mask)) return i + @ctz(~blank);
|
||||||
|
}
|
||||||
|
while (i < text.len and (text[i] == ' ' or text[i] == '\t')) i += 1;
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Index of the first '\n' at or after `start`, or text.len.
|
||||||
|
pub fn findNewline(text: []const u8, start: usize) usize {
|
||||||
|
return std.mem.indexOfScalarPos(u8, text, start, '\n') orelse text.len;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Index just past the `*/` closing a block comment whose body starts at
|
||||||
|
/// `start`, or text.len if it is unterminated.
|
||||||
|
pub fn skipBlockComment(text: []const u8, start: usize) usize {
|
||||||
|
var i = start;
|
||||||
|
while (std.mem.indexOfScalarPos(u8, text, i, '*')) |star| {
|
||||||
|
if (star + 1 < text.len and text[star + 1] == '/') return star + 2;
|
||||||
|
i = star + 1;
|
||||||
|
}
|
||||||
|
return text.len;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Append the offset of the byte after every '\n' in `text`.
|
||||||
|
pub fn appendLineStarts(gpa: std.mem.Allocator, list: *std.ArrayList(u32), text: []const u8) !void {
|
||||||
|
var i: usize = 0;
|
||||||
|
while (i + vec_len <= text.len) : (i += vec_len) {
|
||||||
|
var m = bits(load(text, i) == @as(V, @splat('\n')));
|
||||||
|
if (m == 0) continue;
|
||||||
|
try list.ensureUnusedCapacity(gpa, @popCount(m));
|
||||||
|
while (m != 0) : (m &= m - 1) {
|
||||||
|
list.appendAssumeCapacity(@intCast(i + @ctz(m) + 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while (i < text.len) : (i += 1) {
|
||||||
|
if (text[i] == '\n') try list.append(gpa, @intCast(i + 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Number of '\n' bytes in `text`.
|
||||||
|
pub fn countNewlines(text: []const u8) usize {
|
||||||
|
var n: usize = 0;
|
||||||
|
var i: usize = 0;
|
||||||
|
while (i + vec_len <= text.len) : (i += vec_len) {
|
||||||
|
n += @popCount(bits(load(text, i) == @as(V, @splat('\n'))));
|
||||||
|
}
|
||||||
|
while (i < text.len) : (i += 1) n += @intFromBool(text[i] == '\n');
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Character classes for the scalar lexer paths (identifiers are usually
|
||||||
|
/// shorter than a vector, so a table lookup beats SIMD there).
|
||||||
|
pub const ident_char: [256]bool = blk: {
|
||||||
|
var t: [256]bool = @splat(false);
|
||||||
|
for ('a'..'z' + 1) |c| t[c] = true;
|
||||||
|
for ('A'..'Z' + 1) |c| t[c] = true;
|
||||||
|
for ('0'..'9' + 1) |c| t[c] = true;
|
||||||
|
t['_'] = true;
|
||||||
|
break :blk t;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Index of the first non-identifier byte at or after `start`.
|
||||||
|
pub fn skipIdent(text: []const u8, start: usize) usize {
|
||||||
|
var i = start;
|
||||||
|
while (i < text.len and ident_char[text[i]]) i += 1;
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn refLineStarts(gpa: std.mem.Allocator, text: []const u8) ![]u32 {
|
||||||
|
var l: std.ArrayList(u32) = .empty;
|
||||||
|
for (text, 0..) |c, i| if (c == '\n') try l.append(gpa, @intCast(i + 1));
|
||||||
|
return l.toOwnedSlice(gpa);
|
||||||
|
}
|
||||||
|
|
||||||
|
test "vector scans agree with scalar references" {
|
||||||
|
const gpa = std.testing.allocator;
|
||||||
|
var prng = std.Random.DefaultPrng.init(0x5eed);
|
||||||
|
const r = prng.random();
|
||||||
|
const alphabet = " \t\n/*ab_9\"\\";
|
||||||
|
for (0..300) |_| {
|
||||||
|
const len = r.uintLessThan(usize, 200);
|
||||||
|
const text = try gpa.alloc(u8, len);
|
||||||
|
defer gpa.free(text);
|
||||||
|
for (text) |*c| c.* = alphabet[r.uintLessThan(usize, alphabet.len)];
|
||||||
|
const start = if (len == 0) 0 else r.uintLessThan(usize, len);
|
||||||
|
|
||||||
|
var blanks = start;
|
||||||
|
while (blanks < len and (text[blanks] == ' ' or text[blanks] == '\t')) blanks += 1;
|
||||||
|
try std.testing.expectEqual(blanks, skipBlanks(text, start));
|
||||||
|
|
||||||
|
const ref_end = if (std.mem.indexOfPos(u8, text, start, "*/")) |e| e + 2 else len;
|
||||||
|
try std.testing.expectEqual(ref_end, skipBlockComment(text, start));
|
||||||
|
|
||||||
|
const ref = try refLineStarts(gpa, text);
|
||||||
|
defer gpa.free(ref);
|
||||||
|
var got: std.ArrayList(u32) = .empty;
|
||||||
|
defer got.deinit(gpa);
|
||||||
|
try appendLineStarts(gpa, &got, text);
|
||||||
|
try std.testing.expectEqualSlices(u32, ref, got.items);
|
||||||
|
try std.testing.expectEqual(ref.len, countNewlines(text));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -2,6 +2,7 @@
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const Allocator = std.mem.Allocator;
|
const Allocator = std.mem.Allocator;
|
||||||
|
const scan = @import("scan.zig");
|
||||||
|
|
||||||
pub const FileId = u32;
|
pub const FileId = u32;
|
||||||
|
|
||||||
|
|
@ -147,10 +148,9 @@ pub const SourceManager = struct {
|
||||||
const no_bom = if (std.mem.startsWith(u8, raw, "\xEF\xBB\xBF")) raw[3..] else raw;
|
const no_bom = if (std.mem.startsWith(u8, raw, "\xEF\xBB\xBF")) raw[3..] else raw;
|
||||||
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.append(a, 0);
|
try starts.ensureTotalCapacity(a, text.len / 32 + 16);
|
||||||
for (text, 0..) |c, i| {
|
starts.appendAssumeCapacity(0);
|
||||||
if (c == '\n') try starts.append(a, @intCast(i + 1));
|
try scan.appendLineStarts(a, &starts, text);
|
||||||
}
|
|
||||||
const content = try a.create(Content);
|
const content = try a.create(Content);
|
||||||
content.* = .{ .text = text, .line_starts = try starts.toOwnedSlice(a) };
|
content.* = .{ .text = text, .line_starts = try starts.toOwnedSlice(a) };
|
||||||
return content;
|
return content;
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@ pub const Diagnostics = @import("diag.zig").Diagnostics;
|
||||||
pub const front = struct {
|
pub const front = struct {
|
||||||
pub const source = @import("front/source.zig");
|
pub const source = @import("front/source.zig");
|
||||||
pub const lexer = @import("front/lexer.zig");
|
pub const lexer = @import("front/lexer.zig");
|
||||||
|
pub const scan = @import("front/scan.zig");
|
||||||
pub const preproc = @import("front/preproc.zig");
|
pub const preproc = @import("front/preproc.zig");
|
||||||
pub const pp_print = @import("front/pp_print.zig");
|
pub const pp_print = @import("front/pp_print.zig");
|
||||||
};
|
};
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue