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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie <jeff@ocjtech.us>//// SPDX-License-Identifier: MIT
//! A file that says how to set a machine up, so that nobody has to remember//! twenty switches.//!//! Both front ends here take a long line of flags — a ROM, a disk controller's//! firmware, two floppies, a hard disk, which monitor, which card in slot 4 —//! and most of them do not change from one run to the next. This is the same//! set of settings written down once and pointed at with `--config`.//!//! The format is [Ziggy](https://ziggy-lang.io), which is a small typed//! language for exactly this: a document is a struct, a field is `.name =//! value`, comments start with `//`, and a program gets a Zig struct out of it//! rather than a bag of strings. What that buys over a hand-rolled reader is//! the part nobody enjoys writing — it knows the difference between a number//! and a string and says so, and it reports where in the file the trouble is//! rather than that there was some.//!//! ```ziggy//! .rom = "roms/apple2e.rom",//! .monitor = "colour",//! .slots = [//! .{ .slot = 6, .card = "disk", .rom = "roms/341-0027-a.p5",//! .disk1 = "disks/game.dsk" },//! .{ .slot = 4, .card = "mouse" },//! ],//! ```//!//! **A card is described where it sits and nowhere else.** That is what makes a//! machine with two of a kind expressible at all: a controller in slot 5 and//! another in 6, each with its own disks, and nowhere for a single `.disk_rom`//! at the top of the file to have meant both.//!//! Everything in a config is optional, and a switch on the command line beats//! the file, so a file is a starting point rather than a straitjacket: keep the//! machine in the file and say `--disk1 other.dsk` when you want a different//! disk in it today.//!//! One file serves both programs. The two machines want different things — a//! IIe has slots and a controller card to load firmware into, a IIgs has its//! drives built in — so each takes the settings that apply to it and says so//! when the file asks for something it cannot do. That is better than two//! formats, and better than a file that silently does nothing.
const std = @import("std");
const ziggy = @import("ziggy");
/// One disk in the library: a friendly name to show in the picker, the file/// it stands for, and whether the machine may write to it.////// The name is what makes a library worth having — "Wizardry Scenario" reads/// where a path does not — and it is what the picker lists. Writability is per/// disk rather than one switch for the machine, because a boot disk wants/// keeping pristine while the character disk beside it must be written to, and/// the two go in the same drive one after the other. Absent, it is read only,/// which is the safe assumption for a library of originals.pub const Disk = struct { name: []const u8, path: []const u8, writable: ?bool = null,};
/// A card, and the slot it is in.////// This is how a file describes a card, and the only way: what a card needs is/// written down beside where the card is, rather than at the top of the file in/// a field named after the card. That is what makes two of a kind expressible/// at all — a machine can have a controller in slot 5 and another in 6, each/// with its own disks in it, and there is nowhere for `.disk_rom` to have meant/// both.////// Most of the fields below apply to some cards and not others: `.charset` is/// meaningless on a disk controller, and a machine given one is told so rather/// than having it quietly ignored. See `.ziggy-schema` at the top of the/// repository, which is what an editor reads.pub const Slot = struct { /// Which slot, 1 to 7. Slot 0 is not a slot. slot: u8, /// What is in it: `disk`, `serial`, `videx`, `ultraterm`, `mouse`, /// `mockingboard`, `phasor`, `soundspeech`, `passport`, `uthernet`, /// `uthernet1`, `clock`, /// `ramfactor`, `block`, `transporter` or `parallel`. The same names /// `--slot` takes. card: []const u8,
/// The card's own firmware, for the cards that have some and whose ROM is /// somebody else's: a Disk II's boot PROM, a Super Serial Card's two /// kilobytes, a Videoterm's kilobyte, an UltraTerm's four, a RamFactor's /// eight, a Transporter's PROM. The cards whose firmware is ours — the /// mouse, the clock, the printer card, the block device — need none. rom: ?[]const u8 = null, /// An eighty-column card's character generator, and a second one for a /// Videoterm modified to take one. charset: ?[]const u8 = null, alternate: ?[]const u8 = null,
/// A disk controller's drives, and what is in them. The card only ever had /// two connectors. drives: ?u8 = null, disk1: ?[]const u8 = null, disk2: ?[]const u8 = null,
/// A block device's two volumes. image: ?[]const u8 = null, image2: ?[]const u8 = null,
/// Where a printer card's output goes, and the two ends of a serial card's /// wire. out: ?[]const u8 = null, in: ?[]const u8 = null, /// Whether a Hayes modem is on the serial card's line, dialing over TCP, /// instead of the files above. modem: ?bool = null,
/// How much memory is on a RamFactor, as a size like "1M" or "512K", and /// the file its contents are kept in between runs if the battery option is /// fitted. memory: ?[]const u8 = null, battery: ?[]const u8 = null,
/// How many hours a clock card is from UTC, since the host's clock is read /// as UTC and the machine knows nothing of time zones. offset: ?i8 = null,
/// The number a Transporter answers `Who Am I` with, which on the real /// board is a DIP switch on it. node: ?u8 = null,};
/// Every setting either program understands, and none of them required.////// The names are the long flags with their dashes turned into underscores,/// which is the one naming rule worth having here: anything you can find in/// `--help` you can write in the file, spelled the same way.////// Cards are the exception, and deliberately: they are in `.slots` and nowhere/// else, because a card's settings belong beside the slot it is in rather than/// at the top of a file that can only name each kind once.pub const Config = struct { /// Which Apple to be — `flat`, `i`, `ii`, `ii+`, `iie`, `iic`, `iii`, `iii+` or /// `iigs` — and what to /// put in its socket: `6502`, `RP2A03`, `65C02`, `R65C02` or `W65C02`. A /// IIgs has a 65816 and no say in the matter, so it ignores the second. machine: ?[]const u8 = null, processor: ?[]const u8 = null,
/// The machine's own ROM, which nothing can guess. rom: ?[]const u8 = null,
/// A IIe's character generator, "original" or "enhanced", when the one that /// matches its ROM is not the one wanted. video_rom: ?[]const u8 = null,
/// The cards in the machine, and what is in each of them. slots: ?[]const Slot = null,
/// An Apple-1 Cassette Interface's 256 byte PROM, which fits the card — /// and with it the machine's only cassette port. Not a slot: an Apple-1 is /// the one machine here whose card is not one of the seven. aci_rom: ?[]const u8 = null,
/// What goes in the drives a machine has of its own, rather than on a /// card: a IIc's, a IIgs's, an Apple III's. On a machine with slots a disk /// belongs to a controller, and goes in that card's entry in `.slots`. disk1: ?[]const u8 = null, disk2: ?[]const u8 = null, /// And the intelligent drives on a IIgs's disk port. A IIc reaches its /// through `.disk1`, by the size of the image. unidisk: ?[]const u8 = null, unidisk2: ?[]const u8 = null, /// Whether a disk may be written to, and saved back to its file. writable: ?bool = null,
/// A library of disks to choose between without typing a path. The picker /// on `alt-1` and `alt-2` lists these by name, so the several floppies a /// game is spread across are a keystroke apart. Each entry says whether the /// machine may write to that disk. library: ?[]const Disk = null,
/// Where a picture of the screen goes when one is asked for. screenshot: ?[]const u8 = null, /// A save state to boot straight into: the machine is built the ordinary /// way from everything else here, and then the snapshot is read on top of /// it, so it comes up exactly where it was saved. `alt+w` writes one of /// these beside every snapshot it takes. snapshot: ?[]const u8 = null, /// Which monitor the machine is being looked at on: `monochrome` or /// `colour`. monitor: ?[]const u8 = null, /// Who draws the text: `pixels` for the machine's own character generator /// or `terminal` for the terminal's letters. text: ?[]const u8 = null, /// Whether to start stopped rather than running. halted: ?bool = null,
/// Recording what the speaker did to a `.wav`, and the tape either way in /// or out of one. These stay whatever live audio does: `audio` writes a /// file, `cassette_in` reads one, `cassette_out` writes one. audio: ?[]const u8 = null, cassette_in: ?[]const u8 = null, cassette_out: ?[]const u8 = null,
/// Live audio: the machine's sound out of a real speaker. On where the /// platform and a running daemon allow it; `false` keeps it quiet. This is /// separate from `audio` above, which records to a file regardless. sound: ?bool = null, /// Whether a fitted Mockingboard has an SSI 263A speech chip in its socket. speech: ?bool = null, /// How loud live audio starts, nought to a hundred. Left unset it is the /// built-in default; the keys that work the volume move it from here. volume: ?u8 = null, /// Whether live audio starts muted, the volume kept for when it is /// unmuted. mute: ?bool = null,
/// How much RAM the machine has, as a size like "1M", "512K" or "48K". A /// IIgs counts the Mega II's 128K; an Apple II or II Plus counts its rows /// of chips, in the configurations Apple sold, and "12K-hires" is the /// Apple II's twelve kilobytes laid out under the Hi-Res page. memory: ?[]const u8 = null, /// A IIc's memory expansion, which is a connector inside the case rather /// than a slot, so it is the machine's setting and not a card's. memory_expansion: ?[]const u8 = null, /// An Apple-1 counts its two banks: "4K" or "8K". /// Which Apple II board: 0 for the first boards, 1 for every one after. revision: ?u8 = null,
/// A IIgs's printer port, which is the SCC's other channel rather than a /// card in a slot. printer_out: ?[]const u8 = null,
/// A IIgs on a LocalTalk network, the log of what crossed it, the /// Control Panel set to AppleTalk, and where the parameter RAM is kept. localtalk: ?bool = null, localtalk_log: ?[]const u8 = null, localtalk_interface: ?[]const u8 = null, appletalk: ?bool = null, battery_ram: ?[]const u8 = null,
/// An Uthernet's virtual Ethernet: the interface to carry it on, and a /// hardware address for whichever Ethernet card is fitted. ethernet_interface: ?[]const u8 = null, mac: ?[]const u8 = null,};
pub const Error = error{ /// The file is there and is not a configuration. NotAConfig,};
/// What went wrong, in enough detail to point at it.////// Ziggy hands back the line and column, which is the whole reason for using/// it rather than counting commas by hand, and a missing field's name when/// that is the trouble.pub const Trouble = struct { path: []const u8, line: u32 = 0, column: u32 = 0, what: []const u8 = "",
pub fn say(self: Trouble) void { if (self.line == 0) { std.debug.print("{s}: {s}\n", .{ self.path, self.what }); } else { std.debug.print("{s}:{d}:{d}: {s}\n", .{ self.path, self.line, self.column, self.what, }); } }};
/// Reads a configuration, or says where it could not.////// The strings in what comes back point into the buffer this allocates, which/// is never freed: a program that has read its configuration keeps it for as/// long as it runs, and the alternative is copying every path twice over to no/// purpose.pub fn read( io: std.Io, gpa: std.mem.Allocator, path: []const u8, trouble: *Trouble,) !Config { trouble.* = .{ .path = path };
const bytes = std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 20)) catch |err| { trouble.what = switch (err) { error.FileNotFound => "no such file", error.AccessDenied => "not allowed to read it", error.IsDir => "that is a directory", else => @errorName(err), }; return err; }; const text = try gpa.allocSentinel(u8, bytes.len, 0); @memcpy(text, bytes); gpa.free(bytes);
var meta: ziggy.Deserializer.Meta = undefined; return ziggy.deserializeLeaky(Config, gpa, text, &meta, .{}) catch |err| { trouble.line = meta.error_loc.getSelection(text).start.line; trouble.column = meta.error_loc.getSelection(text).start.col; // The reader's own words rather than the library's, since these are // read by whoever wrote the file and not by a programmer. trouble.what = switch (err) { error.UnknownField => "no such setting", error.DuplicateField => "that setting is given twice", error.MissingField => meta.missing_field_name, error.Unexpected => "the wrong kind of value for this setting", error.Overflow => "that number is too big for this setting", else => @errorName(err), }; return error.NotAConfig; };}
/// The path a companion config goes to: a snapshot's path with its extension/// changed to `.ziggy`, so `game.z65` gets `game.ziggy` beside it.pub fn companionPath(gpa: std.mem.Allocator, snapshot_path: []const u8) ![]const u8 { const ext = std.fs.path.extension(snapshot_path); const stem = snapshot_path[0 .. snapshot_path.len - ext.len]; return std.fmt.allocPrint(gpa, "{s}.ziggy", .{stem});}
/// Writes a config to a file, so a save state can be booted straight into with/// `--config`. Only the settings that are actually set are written; a reader/// defaults the rest, the same as a config anyone writes by hand.pub fn write(io: std.Io, gpa: std.mem.Allocator, path: []const u8, cfg: Config) !void { var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); try out.writer.writeAll( \\// Written by zig65 beside a save state. `zig65 --config <this file>` \\// builds the machine from these settings and boots into the snapshot. \\ \\ ); try ziggy.serialize(cfg, .{ .emit_null_fields = false }, &out.writer); try out.writer.writeByte('\n'); try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = out.written() });}
const testing = std.testing;
/// Reads a configuration out of a string, which is what the tests want and/// what `read` does once it has the file.fn readText(gpa: std.mem.Allocator, text: [:0]const u8) !Config { var meta: ziggy.Deserializer.Meta = undefined; return ziggy.deserializeLeaky(Config, gpa, text, &meta, .{});}
test "a config written for a save state reads back the machine it holds" { const alloc = testing.allocator; const cfg: Config = .{ .machine = "iie", .rom = "apple2e.rom", .memory = "128K", .slots = &.{.{ .slot = 6, .card = "disk", .rom = "p5.bin" }}, .snapshot = "game.z65", };
// Serialize the way `write` does, then read it back the way `read` does. var out: std.Io.Writer.Allocating = .init(alloc); defer out.deinit(); try ziggy.serialize(cfg, .{ .emit_null_fields = false }, &out.writer); const text = try alloc.allocSentinel(u8, out.written().len, 0); defer alloc.free(text); @memcpy(text, out.written());
var arena: std.heap.ArenaAllocator = .init(alloc); defer arena.deinit(); const back = try readText(arena.allocator(), text);
try testing.expectEqualStrings("iie", back.machine.?); try testing.expectEqualStrings("apple2e.rom", back.rom.?); try testing.expectEqualStrings("128K", back.memory.?); try testing.expectEqualStrings("game.z65", back.snapshot.?); try testing.expectEqual(@as(usize, 1), back.slots.?.len); try testing.expectEqual(@as(u8, 6), back.slots.?[0].slot); try testing.expectEqualStrings("disk", back.slots.?[0].card); try testing.expectEqualStrings("p5.bin", back.slots.?[0].rom.?); // A setting left null is not written, and reads back null. try testing.expectEqual(@as(?[]const u8, null), back.processor);}
test "a configuration says what it says and nothing else" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit();
const config = try readText(arena.allocator(), \\// An Apple IIe with a game in the first drive. \\.machine = "iie", \\.rom = "roms/apple2e.rom", \\.monitor = "colour", \\.slots = [ \\ .{ .slot = 6, .card = "disk", .rom = "roms/341-0027-a.p5", \\ .drives = 2, .disk1 = "disks/game.dsk" }, \\ .{ .slot = 4, .card = "mouse" }, \\], \\ ); try testing.expectEqualStrings("iie", config.machine.?); try testing.expectEqualStrings("roms/apple2e.rom", config.rom.?); try testing.expectEqualStrings("colour", config.monitor.?);
const slots = config.slots.?; try testing.expectEqual(@as(usize, 2), slots.len); try testing.expectEqual(@as(u8, 6), slots[0].slot); try testing.expectEqualStrings("disk", slots[0].card); try testing.expectEqualStrings("roms/341-0027-a.p5", slots[0].rom.?); try testing.expectEqual(@as(?u8, 2), slots[0].drives); try testing.expectEqualStrings("disks/game.dsk", slots[0].disk1.?); // A card that needs nothing says nothing. try testing.expectEqualStrings("mouse", slots[1].card); try testing.expectEqual(@as(?[]const u8, null), slots[1].rom);
// Everything it did not say is still nothing, which is what lets a switch // on the command line beat the file without having to know whether the // file mentioned it. try testing.expectEqual(@as(?[]const u8, null), config.disk1); try testing.expectEqual(@as(?[]const u8, null), slots[0].disk2); try testing.expectEqual(@as(?[]const u8, null), slots[0].charset);}
test "two cards of one kind, which is what a slot entry is for" { // The reason a card is described where it sits rather than in a field // named after it: there is nowhere for one `.disk_rom` at the top of a // file to have meant two controllers with different disks in them. var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit();
const config = try readText(arena.allocator(), \\.machine = "iie", \\.slots = [ \\ .{ .slot = 5, .card = "disk", .rom = "p5.rom", .disk1 = "scratch.dsk" }, \\ .{ .slot = 6, .card = "disk", .rom = "p5.rom", .disk1 = "boot.dsk" }, \\], \\ ); const slots = config.slots.?; try testing.expectEqual(@as(usize, 2), slots.len); try testing.expectEqualStrings("disk", slots[0].card); try testing.expectEqualStrings("disk", slots[1].card); try testing.expectEqualStrings("scratch.dsk", slots[0].disk1.?); try testing.expectEqualStrings("boot.dsk", slots[1].disk1.?);}
test "the flat card fields are gone, and a file still using one is told" { // They were one field per kind of card at the top of the file, which could // only ever describe one of each. Leaving them in as well would have been // two ways to say one thing and no way to say the thing they cannot. var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit();
for ([_][:0]const u8{ ".disk_rom = \"p5.rom\",\n", ".mouse = true,\n", ".videx_rom = \"videx.rom\",\n", ".hard_disk = \"hd.2mg\",\n", ".clock = true,\n", ".ramfactor_rom = \"rf.rom\",\n", }) |text| { try testing.expectError(error.UnknownField, readText(arena.allocator(), text)); }}
test "an empty configuration is a configuration" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit();
const config = try readText(arena.allocator(), ""); try testing.expectEqual(@as(?[]const u8, null), config.rom); try testing.expectEqual(@as(?[]const Slot, null), config.slots);}
test "a IIgs configuration and an 8-bit one are the same file" { // The two machines want different things and the file has room for both: // each program takes what applies to it. This one would drive gs. var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit();
const config = try readText(arena.allocator(), \\.rom = "roms/iigs-01.bin", \\.disk1 = "disks/boot800.po", \\.text = "terminal", \\.slots = [ \\ .{ .slot = 7, .card = "block", .image = "disks/system.2mg", \\ .image2 = "disks/work.po" }, \\], \\ ); try testing.expectEqualStrings("roms/iigs-01.bin", config.rom.?); try testing.expectEqualStrings("terminal", config.text.?); // A IIgs's floppy drives are its own rather than a card's, so the disk in // one is a setting of the machine. Its block device is a card in slot 7, // and is where a card is described: in the slot it is in. try testing.expectEqualStrings("disks/boot800.po", config.disk1.?); const slots = config.slots.?; try testing.expectEqualStrings("block", slots[0].card); try testing.expectEqualStrings("disks/system.2mg", slots[0].image.?); try testing.expectEqualStrings("disks/work.po", slots[0].image2.?);}
test "a library is a list of named disks" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit();
const config = try readText(arena.allocator(), \\.machine = "iie", \\.library = [ \\ .{ .name = "Wizardry Boot", .path = "disks/wiz-boot.woz" }, \\ .{ .name = "Scenario Disk A", .path = "disks/wiz-a.dsk", .writable = true }, \\], \\ );
const library = config.library.?; try testing.expectEqual(@as(usize, 2), library.len); try testing.expectEqualStrings("Wizardry Boot", library[0].name); try testing.expectEqualStrings("disks/wiz-boot.woz", library[0].path); // A disk that says nothing about writing is read only. try testing.expectEqual(@as(?bool, null), library[0].writable); try testing.expectEqualStrings("Scenario Disk A", library[1].name); try testing.expectEqual(@as(?bool, true), library[1].writable);}
test "a field that is not a setting is refused rather than ignored" { // Which is the point of a typed format: a mistyped name is a mistake and // should be said so, not quietly do nothing for the rest of the day. var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit();
try testing.expectError(error.UnknownField, readText(arena.allocator(), \\.rom = "roms/apple2e.rom", \\.disks = "disks/game.dsk", \\ ));}
test "a setting of the wrong kind is refused too" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit();
// A path is a string and a count is a number, and neither will stand in // for the other. try testing.expectError(error.Unexpected, readText(arena.allocator(), \\.rom = 2, \\ )); try testing.expectError(error.Unexpected, readText(arena.allocator(), \\.writable = "yes", \\ )); // Inside a slot as well as at the top level. try testing.expectError(error.Unexpected, readText(arena.allocator(), \\.slots = [.{ .slot = 6, .card = "disk", .drives = "two" }], \\ )); // And a slot must say which slot and which card: those two are the only // fields of an entry that are not optional, because an entry without them // does not describe anything. try testing.expectError(error.MissingField, readText(arena.allocator(), \\.slots = [.{ .card = "disk" }], \\ )); try testing.expectError(error.MissingField, readText(arena.allocator(), \\.slots = [.{ .slot = 6 }], \\ ));}
/// The schema an editor reads, and the two example files, embedded so that the/// tests below can hold them up against each other. See `build.zig`.const schema_source = @embedFile("schema");const examples = [_][:0]const u8{ @embedFile("apple2e.ziggy"), @embedFile("iigs.ziggy"),};
test "the schema an editor reads is a schema" { // `.ziggy-schema` at the top of the repository is what the Ziggy language // server checks a file against while somebody is writing one. Nothing in // this program reads it, so without a test it could rot into nonsense and // only an editor would ever say so. // // What is checked here is that it parses. What is *not* checked is that // the shipped examples validate against it, and that is worth writing // down rather than leaving as an omission: the validator in the Ziggy this // is pinned to has no notion of a field that may be left out, so every // `?bytes` in a schema is a field a document must still mention. Upstream // fixed exactly that -- "fields of outer type '?', '{:}' and '[]' can be // omitted" -- but the release with the fix wants Zig 0.17 to build, and // this is pinned to 0.16. The editors people actually run carry their own // Ziggy and are ahead of this, which is why the file is still worth // shipping; the test below is what keeps it honest in the meantime. var schema = try ziggy.schema.Ast.init(testing.allocator, schema_source); defer schema.deinit(testing.allocator); if (schema.errors.len > 0) { for (schema.errors) |err| { const at = err.main_location.getSelection(schema_source); std.debug.print(".ziggy-schema:{d}:{d}: {any}\n", .{ at.start.line, at.start.col, err.tag }); } return error.SchemaIsWrong; }
// And that the examples are documents, since a broken one would be found // by whoever copied it rather than by us. for (examples) |source| { var document = try ziggy.Ast.init(testing.allocator, source, .{}); defer document.deinit(testing.allocator); try testing.expectEqual(@as(usize, 0), document.errors.len); }}
test "the schema and Config describe the same settings" { // Two descriptions of one thing drift, and nothing would say so: a field // added to `Config` and forgotten here is a field an editor calls a // mistake, and one taken out is a field an editor still offers. So they // are compared both ways, name by name. // // The comparison is textual rather than through the schema's AST, which // does not expose its field names. That is enough for the failure this is // guarding against, which is a name in one place and not the other. inline for (@typeInfo(Config).@"struct".fields) |field| { const wanted = "\n " ++ field.name ++ ":"; if (std.mem.indexOf(u8, schema_source, wanted) == null) { std.debug.print("`.{s}` is a setting and the schema does not know it\n", .{field.name}); return error.SchemaIsBehind; } } inline for (@typeInfo(Slot).@"struct".fields) |field| { const wanted = "\n " ++ field.name ++ ":"; if (std.mem.indexOf(u8, schema_source, wanted) == null) { std.debug.print("`.{s}` is a slot setting and the schema does not know it\n", .{field.name}); return error.SchemaIsBehind; } }
// And the other way: every field the schema declares has to be a real // setting, or a file an editor accepts is a file the program refuses. var lines = std.mem.splitScalar(u8, schema_source, '\n'); while (lines.next()) |line| { if (!std.mem.startsWith(u8, line, " ")) continue; const body = std.mem.trim(u8, line, " "); if (std.mem.startsWith(u8, body, "///")) continue; const colon = std.mem.indexOfScalar(u8, body, ':') orelse continue; const name = body[0..colon]; var known = false; inline for (@typeInfo(Config).@"struct".fields) |field| { if (std.mem.eql(u8, name, field.name)) known = true; } inline for (@typeInfo(Slot).@"struct".fields) |field| { if (std.mem.eql(u8, name, field.name)) known = true; } inline for (@typeInfo(Disk).@"struct".fields) |field| { if (std.mem.eql(u8, name, field.name)) known = true; } if (!known) { std.debug.print("the schema declares `{s}`, which is not a setting\n", .{name}); return error.SchemaKnowsTooMuch; } }}