Something went wrong. Try again.
A cycle-accurate Apple II and Apple IIgs emulator written in Zig, usable as both a program and a library.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie <jeff@ocjtech.us>//// SPDX-License-Identifier: MIT
//! Regenerates the README's reference list and bibliography from BibTeX.//!//! The two sections used to be hand-maintained APA prose, which meant a new//! source was added by getting the alphabetical order and the `n.d.-a` letters//! right by eye. They are now generated: `doc/references.bib` and//! `doc/bibliography.bib` are the source of truth, and this renders them into//! the README between the markers//!//! <!-- references:start --> … <!-- references:end -->//! <!-- bibliography:start --> … <!-- bibliography:end -->//!//! Run it through the build: `zig build references` rewrites the README,//! `zig build references -- --check` reports whether it is stale and exits//! non-zero if so, which is what CI can hold the tree to.//!//! ## What is generated and what is not//!//! A citation's *shape* is generated — the author, date, title, edition, type,//! publisher and URL are assembled into an APA line and wrapped to the//! paragraph width — so the one place that decides the house style is here.//! An entry's *annotation* is not: it is the prose in the `annotation` field,//! passed through verbatim and only re-indented, because that prose is the//! point of the entry and is written by hand.//!//! Entries are rendered in the order they appear in the `.bib` file, so the//! file's order is the README's order — there is no sorting here, and the//! `n.d.-a`/`n.d.-b` letters are whatever the entries carry.
const std = @import("std");
/// The paragraph width the README wraps prose to. A citation is wrapped to it;/// a URL that is longer than a line is left to overflow, as a URL cannot break,/// which is what the hand-written entries did too.const width = 80;
const Field = struct { name: []const u8, value: []const u8 };
const Entry = struct { fields: std.ArrayList(Field),
fn get(self: Entry, name: []const u8) ?[]const u8 { for (self.fields.items) |f| if (std.mem.eql(u8, f.name, name)) return f.value; return null; }};
/// A minimal BibTeX reader: `@type{key,\n field = {value},\n …\n}`. Values are/// brace-delimited and may run over many lines and hold nested braces, which is/// what lets an `annotation` be a paragraph. `@Comment{…}` blocks (the SPDX/// header) and whitespace between entries are skipped.const Parser = struct { src: []const u8, at: usize = 0,
fn skipSpace(self: *Parser) void { while (self.at < self.src.len and std.ascii.isWhitespace(self.src[self.at])) self.at += 1; }
/// Reads a brace-delimited run, the opening brace already consumed, and /// returns what is between the braces with the matching close consumed. fn braced(self: *Parser) []const u8 { const start = self.at; var depth: usize = 1; while (self.at < self.src.len) : (self.at += 1) { switch (self.src[self.at]) { '{' => depth += 1, '}' => { depth -= 1; if (depth == 0) { const value = self.src[start..self.at]; self.at += 1; // the closing brace return value; } }, else => {}, } } return self.src[start..self.at]; }
fn next(self: *Parser, gpa: std.mem.Allocator) !?Entry { while (true) { self.skipSpace(); if (self.at >= self.src.len) return null; if (self.src[self.at] != '@') { self.at += 1; continue; } self.at += 1; // The entry type, up to the opening brace. const type_start = self.at; while (self.at < self.src.len and self.src[self.at] != '{') self.at += 1; const kind = std.mem.trim(u8, self.src[type_start..self.at], " \t\r\n"); if (self.at >= self.src.len) return null; self.at += 1; // the '{' if (std.ascii.eqlIgnoreCase(kind, "comment")) { _ = self.braced(); continue; } // The cite key, up to the first comma. while (self.at < self.src.len and self.src[self.at] != ',') self.at += 1; self.at += 1; // the ','
var entry: Entry = .{ .fields = .empty }; while (true) { self.skipSpace(); if (self.at >= self.src.len or self.src[self.at] == '}') { if (self.at < self.src.len) self.at += 1; // the entry's '}' break; } const name_start = self.at; while (self.at < self.src.len and self.src[self.at] != '=' and !std.ascii.isWhitespace(self.src[self.at])) self.at += 1; const name = self.src[name_start..self.at]; self.skipSpace(); if (self.at < self.src.len and self.src[self.at] == '=') self.at += 1; self.skipSpace(); if (self.at < self.src.len and self.src[self.at] == '{') { self.at += 1; const value = self.braced(); try entry.fields.append(gpa, .{ .name = name, .value = value }); self.skipSpace(); if (self.at < self.src.len and self.src[self.at] == ',') self.at += 1; } } return entry; } }};
/// Assembles an entry's APA citation line, unwrapped: everything but the/// annotation, as one string ready to be wrapped.fn citation(gpa: std.mem.Allocator, entry: Entry) ![]const u8 { var out: std.Io.Writer.Allocating = .init(gpa); const w = &out.writer;
const author = entry.get("author"); const year = entry.get("year") orelse "n.d."; const title = entry.get("title") orelse "";
const edition = entry.get("edition"); const kind = entry.get("type"); if (author) |a| { // A chapter in a book leads with the chapter, then "In" and the book as // the (italic) title; a plain work is just the title. if (entry.get("chapter")) |ch| { try w.print("{s} ({s}). {s}. In *{s}*", .{ a, year, ch, title }); } else { try w.print("{s} ({s}). *{s}*", .{ a, year, title }); } if (edition) |e| try w.print(" ({s})", .{e}); if (kind) |t| try w.print(" [{s}]", .{t}); try w.writeAll("."); } else { // Title-first: no author, so the title leads and the date follows it — // and a type bracket sits between the title and the date. try w.print("*{s}*", .{title}); if (kind) |t| try w.print(" [{s}]", .{t}); try w.print(". ({s})", .{year}); if (edition) |e| try w.print(" ({s})", .{e}); try w.writeAll("."); } if (entry.get("publisher")) |p| try w.print(" {s}", .{p}); if (entry.get("url")) |u| try w.print(" <{s}>", .{u}); if (entry.get("archiveurl")) |u| try w.print(" (Archived at <{s}>)", .{u});
return out.written();}
/// Wraps `text` to the paragraph width as a Markdown list item: `- ` before the/// first line, two spaces before each that follows. A word longer than a line —/// a URL — is left whole on its own line rather than broken.fn wrapItem(gpa: std.mem.Allocator, text: []const u8) ![]const u8 { var out: std.Io.Writer.Allocating = .init(gpa); const w = &out.writer; var column: usize = 0; var line_start = true; var words = std.mem.tokenizeScalar(u8, text, ' '); while (words.next()) |word| { if (line_start) { try w.print("- {s}", .{word}); column = 2 + word.len; line_start = false; } else if (column + 1 + word.len > width) { try w.print("\n {s}", .{word}); column = 2 + word.len; } else { try w.print(" {s}", .{word}); column += 1 + word.len; } } return out.written();}
/// Renders one section's worth of entries, each a wrapped citation, a blank/// line, and the verbatim annotation indented two spaces, with a blank line/// between entries.fn render(gpa: std.mem.Allocator, entries: []const Entry) ![]const u8 { var out: std.Io.Writer.Allocating = .init(gpa); const w = &out.writer; for (entries, 0..) |entry, i| { if (i != 0) try w.writeAll("\n"); const line = try citation(gpa, entry); try w.print("{s}\n", .{try wrapItem(gpa, line)}); if (entry.get("annotation")) |note| { try w.writeAll("\n"); var lines = std.mem.splitScalar(u8, std.mem.trim(u8, note, "\n"), '\n'); while (lines.next()) |l| { if (l.len == 0) try w.writeAll("\n") else try w.print(" {s}\n", .{l}); } } } return out.written();}
fn readEntries(io: std.Io, gpa: std.mem.Allocator, path: []const u8) ![]Entry { const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 22)); var parser: Parser = .{ .src = bytes }; var list: std.ArrayList(Entry) = .empty; while (try parser.next(gpa)) |entry| try list.append(gpa, entry); return list.items;}
/// Replaces the text between `<!-- name:start -->` and `<!-- name:end -->` with/// `body`, keeping the markers. The section is expected to already exist.fn splice(gpa: std.mem.Allocator, doc: []const u8, name: []const u8, body: []const u8) ![]const u8 { const open = try std.fmt.allocPrint(gpa, "<!-- {s}:start -->", .{name}); const close = try std.fmt.allocPrint(gpa, "<!-- {s}:end -->", .{name}); const a = std.mem.indexOf(u8, doc, open) orelse return error.MarkerMissing; const b = std.mem.indexOf(u8, doc, close) orelse return error.MarkerMissing; var out: std.Io.Writer.Allocating = .init(gpa); try out.writer.print("{s}{s}\n\n{s}\n{s}", .{ doc[0 .. a + open.len], "", body, doc[b..] }); return out.written();}
pub fn main(init: std.process.Init) !void { const io = init.io; var arena_state: std.heap.ArenaAllocator = .init(std.heap.page_allocator); defer arena_state.deinit(); const gpa = arena_state.allocator();
// The build has two steps: `references` rewrites the README, and a check // step passes `--check` to report staleness instead. var check = false; var args: std.process.Args.Iterator = .init(init.minimal.args); _ = args.next(); // the program name while (args.next()) |arg| { if (std.mem.eql(u8, arg, "--check")) check = true; }
const references = try readEntries(io, gpa, "doc/references.bib"); const bibliography = try readEntries(io, gpa, "doc/bibliography.bib");
const original = try std.Io.Dir.cwd().readFileAlloc(io, "README.md", gpa, .limited(1 << 24)); var doc = try splice(gpa, original, "references", try render(gpa, references)); doc = try splice(gpa, doc, "bibliography", try render(gpa, bibliography));
if (check) { if (!std.mem.eql(u8, doc, original)) { std.debug.print("README.md is out of date: run `zig build references`\n", .{}); std.process.exit(1); } return; } try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = "README.md", .data = doc });}