//! Generates the headers that libgpg-error's Makefile builds with awk and a //! throwaway C program. Each command reproduces the output of the upstream //! script named in its doc comment, so the build only needs Zig. const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; const Writer = Io.Writer; const usage = \\Usage: generate [options] \\ \\Commands: \\ strtable mkstrtable.awk; options: textidx=N nogettext prefix=S namespace=S \\ code-to-errno mkerrnos.awk \\ errno-probe mkerrcodes1.awk; the output is meant for the C preprocessor \\ code-from-errno mkerrcodes.awk, mkerrcodes.c and mkerrcodes2.awk over the \\ preprocessed errno-probe output \\ ; pub fn main(init: std.process.Init) !void { const arena = init.arena.allocator(); const args = try init.minimal.args.toSlice(arena); if (args.len < 4) std.process.fatal("{s}", .{usage}); const command = args[1]; const input = try Io.Dir.cwd().readFileAlloc(init.io, args[2], arena, .unlimited); var output: Writer.Allocating = .init(arena); const w = &output.writer; if (std.mem.eql(u8, command, "strtable")) { var options: StrtableOptions = .{}; for (args[4..]) |arg| { if (std.mem.eql(u8, arg, "nogettext")) { options.nogettext = true; } else if (std.mem.startsWith(u8, arg, "textidx=")) { options.textidx = try std.fmt.parseInt(usize, arg["textidx=".len..], 10); } else if (std.mem.startsWith(u8, arg, "prefix=")) { options.prefix = arg["prefix=".len..]; } else if (std.mem.startsWith(u8, arg, "namespace=")) { options.namespace = arg["namespace=".len..]; } else std.process.fatal("unknown strtable option '{s}'", .{arg}); } try strtable(arena, input, w, options); } else if (std.mem.eql(u8, command, "code-to-errno")) { try codeToErrno(arena, input, w); } else if (std.mem.eql(u8, command, "errno-probe")) { try errnoProbe(arena, input, w); } else if (std.mem.eql(u8, command, "code-from-errno")) { try codeFromErrno(arena, input, w); } else std.process.fatal("unknown command '{s}'\n{s}", .{ command, usage }); try Io.Dir.cwd().writeFile(init.io, .{ .sub_path = args[3], .data = output.written() }); } /// An input table in the format shared by upstream's `*.in` files: lines /// starting with '#' are dropped, everything before the first data line is /// copied verbatim, and data lines are split into tab-separated fields after /// their comments and trailing blanks are removed. const Table = struct { header: []const []const u8, rows: []const []const []const u8, fn parse(arena: Allocator, input: []const u8, isFirstRow: *const fn ([]const u8) bool) !Table { var header: std.ArrayList([]const u8) = .empty; var rows: std.ArrayList([]const []const u8) = .empty; var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, input, "\n"), '\n'); while (lines.next()) |line| { if (std.mem.startsWith(u8, line, "#")) continue; if (rows.items.len == 0 and !isFirstRow(firstField(line))) { try header.append(arena, line); continue; } const data = stripComment(line); if (data.len == 0) continue; try rows.append(arena, try splitFields(arena, data)); } if (rows.items.len == 0) return error.NoRows; return .{ .header = header.items, .rows = rows.items }; } fn writeHeader(table: Table, w: *Writer) !void { for (table.header) |line| try w.print("{s}\n", .{line}); } }; fn firstField(line: []const u8) []const u8 { return line[0 .. std.mem.indexOfScalar(u8, line, '\t') orelse line.len]; } /// Mirrors awk's `sub (/#.+/, "")` followed by stripping trailing blanks. fn stripComment(line: []const u8) []const u8 { var data = line; if (std.mem.indexOfScalar(u8, data, '#')) |i| { if (i + 1 < data.len) data = data[0..i]; } return std.mem.trimEnd(u8, data, " \t"); } /// Splits on runs of tabs like awk's `FS = "[\t]+"`, which keeps an empty /// first field when the line starts with a tab. fn splitFields(arena: Allocator, data: []const u8) ![]const []const u8 { var fields: std.ArrayList([]const u8) = .empty; var it = std.mem.splitScalar(u8, data, '\t'); try fields.append(arena, it.first()); while (it.next()) |text| { if (text.len > 0) try fields.append(arena, text); } return fields.items; } /// Returns the 1-based field `index`, or "" like awk does past the end. fn field(row: []const []const u8, index: usize) []const u8 { return if (index >= 1 and index <= row.len) row[index - 1] else ""; } fn isNumber(text: []const u8) bool { if (text.len == 0) return false; for (text) |c| if (!std.ascii.isDigit(c)) return false; return true; } fn startsWithDigit(text: []const u8) bool { return text.len > 0 and std.ascii.isDigit(text[0]); } /// Writes the chain of range checks that maps sparse codes onto dense /// indices, as both mkstrtable.awk and mkerrcodes2.awk do. Returns the last /// range's end and the accumulated skip for an optional default branch. fn writeRanges(w: *Writer, codes: []const i64, line_end: []const u8) !struct { stop: i64, skip: i64 } { var skip = codes[0]; var start = codes[0]; var stop = codes[0]; for (codes[1..]) |code| { if (code == stop + 1) { stop += 1; } else { try w.print(" : ((code >= {d}) && (code <= {d})) ? (code - {d}){s}\n", .{ start, stop, skip, line_end }); skip += code - stop - 1; start = code; stop = code; } } try w.print(" : ((code >= {d}) && (code <= {d})) ? (code - {d}){s}\n", .{ start, stop, skip, line_end }); return .{ .stop = stop, .skip = skip }; } pub const StrtableOptions = struct { textidx: usize = 2, nogettext: bool = false, prefix: []const u8 = "", namespace: []const u8 = "", }; /// mkstrtable.awk: a string table with an index-lookup function. A row /// without a code ends the table and supplies the default message. pub fn strtable(arena: Allocator, input: []const u8, w: *Writer, options: StrtableOptions) !void { const table: Table = try .parse(arena, input, isNumber); try w.writeAll("/* Output of mkstrtable.awk. DO NOT EDIT. */\n\n"); try table.writeHeader(w); try w.writeAll( \\/* The purpose of this complex string table is to produce \\ optimal code with a minimum of relocations. */ \\ \\ ); // Upstream leaves a trailing blank after the '='. try w.print("static const char {s}msgstr[] = \n", .{options.namespace}); var codes: std.ArrayList(i64) = .empty; var positions: std.ArrayList(usize) = .empty; var has_default = false; var position: usize = 0; var last_msgstr: ?[]const u8 = null; for (table.rows) |row| { if (last_msgstr) |msgstr| try writeMsgstr(w, msgstr, options.nogettext, " \"\\0\""); const msgstr = try std.mem.concat(arena, u8, &.{ options.prefix, field(row, options.textidx) }); last_msgstr = msgstr; try positions.append(arena, position); position += msgstr.len + 1; if (field(row, 1).len == 0) { has_default = true; break; } try codes.append(arena, try std.fmt.parseInt(i64, field(row, 1), 10)); } try writeMsgstr(w, last_msgstr.?, options.nogettext, ";"); try w.print("\nstatic const int {s}msgidx[] =\n {{\n", .{options.namespace}); for (positions.items[0..codes.items.len]) |pos| try w.print(" {d},\n", .{pos}); // Without a default row awk prints an unset array element, i.e. nothing. if (has_default) { try w.print(" {d}\n", .{positions.items[codes.items.len]}); } else { try w.writeAll(" \n"); } try w.print( \\ }}; \\ \\static GPG_ERR_INLINE int \\{s}msgidxof (int code) \\{{ \\ return (0 ? 0 \\ , .{options.namespace}); const end = try writeRanges(w, codes.items, ""); if (has_default) { try w.print(" : {d} - {d});\n", .{ end.stop + 1, end.skip }); } else { try w.writeAll(" : -1);\n"); } try w.writeAll("}\n"); } fn writeMsgstr(w: *Writer, msgstr: []const u8, nogettext: bool, suffix: []const u8) !void { if (nogettext) { try w.print(" \"{s}\"{s}\n", .{ msgstr, suffix }); } else { try w.print(" gettext_noop (\"{s}\"){s}\n", .{ msgstr, suffix }); } } const errno_includes = \\#include \\#ifdef _WIN32 \\#include \\#endif \\ \\ ; /// mkerrnos.awk: maps each gpg-error errno code to the system's errno value. fn codeToErrno(arena: Allocator, input: []const u8, w: *Writer) !void { const table: Table = try .parse(arena, input, startsWithDigit); try w.writeAll("/* Output of mkerrnos.awk. DO NOT EDIT. */\n\n"); try table.writeHeader(w); try w.writeAll(errno_includes); try w.writeAll("static const int err_code_to_errno [] = {\n"); for (table.rows) |row| { const name = field(row, 2); try w.print( \\#ifdef {0s} \\ {0s}, \\#else \\#ifdef WSA{0s} \\ WSA{0s}, \\#else \\ 0, \\#endif \\#endif \\ , .{name}); } try w.writeAll("};\n"); } /// mkerrcodes1.awk: pairs every errno name with its gpg-error code name, so /// that running the result through the target's C preprocessor replaces the /// errno names the target defines with their values. fn errnoProbe(arena: Allocator, input: []const u8, w: *Writer) !void { const table: Table = try .parse(arena, input, startsWithDigit); try w.writeAll("/* Output of mkerrcodes.awk. DO NOT EDIT. */\n\n"); try table.writeHeader(w); try w.writeAll(errno_includes); for (table.rows) |row| { const name = field(row, 2); try w.print("#ifdef {0s}\n{0s}\tGPG_ERR_{0s}\n#endif\n" ++ "#ifdef WSA{0s}\nWSA{0s}\tGPG_ERR_{0s}\n#endif\n", .{name}); } } const ErrnoValue = struct { errno: i64, symbol: []const u8, fn lessThan(_: void, a: ErrnoValue, b: ErrnoValue) bool { return a.errno < b.errno; } }; /// The header that mkerrcodes.c prints before its sorted table. const errnos_h_header = \\/* errnos.h - List of system error values. \\ Copyright (C) 2004 g10 Code GmbH \\ This file is part of libgpg-error. \\ \\ libgpg-error is free software; you can redistribute it and/or \\ modify it under the terms of the GNU Lesser General Public License \\ as published by the Free Software Foundation; either version 2.1 of \\ the License, or (at your option) any later version. \\ \\ libgpg-error is distributed in the hope that it will be useful, but \\ WITHOUT ANY WARRANTY; without even the implied warranty of \\ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU \\ Lesser General Public License for more details. \\ \\ You should have received a copy of the GNU Lesser General Public \\ License along with libgpg-error; if not, write to the Free \\ Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA \\ 02111-1307, USA. */ \\ \\ ; /// mkerrcodes.awk, mkerrcodes.c and mkerrcodes2.awk in one: reads the /// preprocessed errno-probe output, sorts it by errno value and emits the /// table that maps system errno values back to gpg-error codes. fn codeFromErrno(arena: Allocator, preprocessed: []const u8, w: *Writer) !void { var values: std.ArrayList(ErrnoValue) = .empty; var lines = std.mem.splitScalar(u8, preprocessed, '\n'); while (lines.next()) |line| { if (std.mem.indexOf(u8, line, "GPG_ERR_") == null) continue; if (std.mem.startsWith(u8, line, "#")) continue; const data = stripComment(line); if (data.len == 0) continue; // Split like awk's `FS = "[ \t]+GPG_ERR_"`. const separator = std.mem.indexOf(u8, data, "GPG_ERR_").?; const value = std.mem.trimEnd(u8, data[0..separator], " \t"); if (value.len == separator) return error.MissingErrnoValue; const name_end = std.mem.indexOfAnyPos(u8, data, separator, " \t") orelse data.len; const errno = std.fmt.parseInt(i64, std.mem.trim(u8, value, " \t"), 10) catch { std.log.err("errno value is not a plain integer: '{s}'", .{line}); return error.UnsupportedErrnoValue; }; try values.append(arena, .{ .errno = errno, .symbol = data[separator..name_end] }); } if (values.items.len == 0) return error.NoErrnoValues; // mkerrcodes.c uses a bubble sort, which keeps aliases in input order. std.sort.insertion(ErrnoValue, values.items, {}, ErrnoValue.lessThan); try w.writeAll("/* Output of mkerrcodes2.awk. DO NOT EDIT. */\n\n"); try w.writeAll(errnos_h_header); try w.writeAll("static const int err_code_from_index[] = {\n"); const codes = try arena.alloc(i64, values.items.len); for (values.items, codes) |value, *code| { try w.print(" {s},\n", .{value.symbol}); code.* = value.errno; } try w.writeAll("};\n\n#define errno_to_idx(code) (0 ? -1 \\\n"); _ = try writeRanges(w, codes, " \\"); try w.writeAll(" : -1)\n"); } pub fn expectGenerated( comptime generate: anytype, input: []const u8, extra: anytype, expected: []const u8, ) !void { var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); var output: Writer.Allocating = .init(arena); try @call(.auto, generate, .{ arena, input, &output.writer } ++ extra); try std.testing.expectEqualStrings(expected, output.written()); } test "strtable with a default row and a gap in the codes" { try expectGenerated(strtable, "# dropped\n" ++ "/* header */\n" ++ "\n" ++ "0\tGPG_ERR_A\tAlpha\n" ++ "1\tGPG_ERR_B\t\tBeta # comment\n" ++ "\n" ++ "5\tGPG_ERR_C\tGamma\n" ++ "\tGPG_ERR_DIM\tUnknown\n", .{StrtableOptions{ .textidx = 3 }}, \\/* Output of mkstrtable.awk. DO NOT EDIT. */ \\ \\/* header */ \\ \\/* The purpose of this complex string table is to produce \\ optimal code with a minimum of relocations. */ \\ \\ ++ "static const char msgstr[] = \n" ++ \\ gettext_noop ("Alpha") "\0" \\ gettext_noop ("Beta") "\0" \\ gettext_noop ("Gamma") "\0" \\ gettext_noop ("Unknown"); \\ \\static const int msgidx[] = \\ { \\ 0, \\ 6, \\ 11, \\ 17 \\ }; \\ \\static GPG_ERR_INLINE int \\msgidxof (int code) \\{ \\ return (0 ? 0 \\ : ((code >= 0) && (code <= 1)) ? (code - 0) \\ : ((code >= 5) && (code <= 5)) ? (code - 3) \\ : 6 - 3); \\} \\ ); } test "strtable without a default row, with prefix and namespace" { try expectGenerated(strtable, "1\tEPERM\n2\tENOENT\n", .{StrtableOptions{ .nogettext = true, .prefix = "GPG_ERR_", .namespace = "errnos_" }}, \\/* Output of mkstrtable.awk. DO NOT EDIT. */ \\ \\/* The purpose of this complex string table is to produce \\ optimal code with a minimum of relocations. */ \\ \\ ++ "static const char errnos_msgstr[] = \n" ++ \\ "GPG_ERR_EPERM" "\0" \\ "GPG_ERR_ENOENT"; \\ \\static const int errnos_msgidx[] = \\ { \\ 0, \\ 14, \\ ++ " \n" ++ \\ }; \\ \\static GPG_ERR_INLINE int \\errnos_msgidxof (int code) \\{ \\ return (0 ? 0 \\ : ((code >= 1) && (code <= 2)) ? (code - 1) \\ : -1); \\} \\ ); } test "code-to-errno" { try expectGenerated(codeToErrno, "/* header */\n0\tE2BIG\n", .{}, \\/* Output of mkerrnos.awk. DO NOT EDIT. */ \\ \\/* header */ \\#include \\#ifdef _WIN32 \\#include \\#endif \\ \\static const int err_code_to_errno [] = { \\#ifdef E2BIG \\ E2BIG, \\#else \\#ifdef WSAE2BIG \\ WSAE2BIG, \\#else \\ 0, \\#endif \\#endif \\}; \\ ); } test "errno-probe" { try expectGenerated(errnoProbe, "0\tE2BIG\n", .{}, \\/* Output of mkerrcodes.awk. DO NOT EDIT. */ \\ \\#include \\#ifdef _WIN32 \\#include \\#endif \\ \\#ifdef E2BIG \\ ++ "E2BIG\tGPG_ERR_E2BIG\n" ++ \\#endif \\#ifdef WSAE2BIG \\ ++ "WSAE2BIG\tGPG_ERR_E2BIG\n" ++ \\#endif \\ ); } test "code-from-errno sorts stably and keeps aliases" { try expectGenerated(codeFromErrno, "# 1 \"probe.h\"\n" ++ "int unrelated;\n" ++ "11 GPG_ERR_EAGAIN\n" ++ "1 GPG_ERR_EPERM\n" ++ "11\tGPG_ERR_EWOULDBLOCK\n" ++ "2 GPG_ERR_ENOENT\n", .{}, "/* Output of mkerrcodes2.awk. DO NOT EDIT. */\n\n" ++ errnos_h_header ++ \\static const int err_code_from_index[] = { \\ GPG_ERR_EPERM, \\ GPG_ERR_ENOENT, \\ GPG_ERR_EAGAIN, \\ GPG_ERR_EWOULDBLOCK, \\}; \\ \\#define errno_to_idx(code) (0 ? -1 \ \\ : ((code >= 1) && (code <= 2)) ? (code - 1) \ \\ : ((code >= 11) && (code <= 11)) ? (code - 9) \ \\ : ((code >= 11) && (code <= 11)) ? (code - 8) \ \\ : -1) \\ ); }