From 58bc2da64fd9c9a73f6fbf20db8cbfa491934773 Mon Sep 17 00:00:00 2001 From: "Jeffrey C. Ollie" Date: Mon, 31 Aug 2026 08:14:09 -0500 Subject: [PATCH] finish the format side of moment.js compatibility Everything moment.js can format, this can now format the same way, bar the zone name. 777266 comparisons, no divergence. Literals stop being a whitelist. Anything that is not a sequence is copied through, which is how moment behaves and which makes `YYYY/MM/DD` work where it used to be a compile error. Square brackets make a literal of what would otherwise be read as a sequence, and a backslash does the same for whatever follows it. The corners are moment's and are followed rather than tidied, because a format string that means one thing there and another here is the whole problem. A `[` with no `]` after it is a literal bracket; so is one that would have to nest, which is why `[a[b]` is a bracket, then `a`, then a bracketed `b`. A backslash before another backslash yields nothing at all, and so does a trailing one, because moment strips every backslash out of the run its regex matched. All of it is in the corpus. Token, which used to be a character or a tag, is now a run of characters or a tag: bracketed text arrives at once, and an escape can produce nothing. New sequences: Y, YYYYY and YYYYYY; y, yo, yy, yyy and yyyy; N through NNNNN; ggggg and GGGGG; X and x; and Hmm, Hmmss, hmm and hmmss, which are single sequences rather than an hour beside a minute and so are not the same as writing the parts. YYY stops being a sequence, because moment reads it as YY followed by Y, and it now does too. The localized sequences -- L, LL, LLL, LLLL, LT, LTS and the four lower case ones -- stand for a whole format string rather than for a value, so they are expanded into what they stand for before anything is tokenized, which is moment's arrangement. The expansions are the `en` locale's, the only locale there is here. X and x needed a DateTime to name an instant, so toInstant is added: the inverse of Instant.asDateTime, and simpler than TimeZone.resolve because a reading with an offset on it cannot be ambiguous or missing. Still absent: z and zz, the zone abbreviation. A DateTime carries an offset and no designation, so there is nothing to write; it needs either a field or formatting through a TimeZone, and that is a data model question rather than a formatting one. Parsing is unchanged. zig build test 202 pass, 4 skip zig build test -Dno-system-tzdata 180 pass, 26 skip zig build test -Dembed-tzdata 206 pass Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01TFydFscsLXY7WWaGL4NKnL --- src/DateTime.zig | 172 ++++++++++++++++++++----- src/formatsequence.zig | 284 +++++++++++++++++++++++++++++++++++++---- tools/oracle_dump.zig | 55 +++++--- 3 files changed, 440 insertions(+), 71 deletions(-) diff --git a/src/DateTime.zig b/src/DateTime.zig index 54bacf3..5543aac 100644 --- a/src/DateTime.zig +++ b/src/DateTime.zig @@ -33,7 +33,8 @@ const Nanosecond = @import("nanosecond.zig").Nanosecond; const DayOfWeek = @import("dayofweek.zig").DayOfWeek; const Date = @import("Date.zig"); const Instant = @import("Instant.zig"); -const FormatTag = @import("formatsequence.zig").FormatTag; +const formatsequence = @import("formatsequence.zig"); +const FormatTag = formatsequence.FormatTag; const writeTwelveHour = @import("hour.zig").writeTwelveHour; const ordinal = @import("ordinal.zig"); const print = @import("print.zig"); @@ -122,6 +123,21 @@ test printYear { try std.testing.expectEqualStrings("-0044", bce.buffered()); } +/// Writes `year` zero padded to `width` digits, with a leading minus for +/// a year before the common era. `printYear` is this at four digits. +fn printPaddedYear(writer: *std.Io.Writer, year: Year, comptime width: usize) !void { + if (year < 0) try writer.writeAll("-"); + try writer.print("{d:0>[1]}", .{ @abs(year), width }); +} + +test printPaddedYear { + var buf: [16]u8 = undefined; + + var five = std.Io.Writer.fixed(&buf); + try printPaddedYear(&five, 2024, 5); + try std.testing.expectEqualStrings("02024", five.buffered()); +} + /// Wraps `val` into the range `[1, at]`, mapping a remainder of 0 to `at` /// (e.g. hour 0 becomes 12 on a 12-hour clock). fn wrap(val: anytype, at: @TypeOf(val)) @TypeOf(val) { @@ -169,16 +185,20 @@ pub fn format(self: DateTime, comptime fmt: []const u8, writer: *std.Io.Writer) @setEvalBranchQuota(2000000); + // The localized sequences stand for other sequences rather than for a + // value, so they are replaced before anything is tokenized. + const expanded = comptime formatsequence.expandLocalized(fmt); + const tokens: []const FormatTag.Tokenizer.Token = comptime tokens: { var count = 0; { - var it: FormatTag.Tokenizer = .init(fmt); + var it: FormatTag.Tokenizer = .init(expanded); while (it.next()) |_| count += 1; } var buf: [count]FormatTag.Tokenizer.Token = undefined; var index = 0; { - var it: FormatTag.Tokenizer = .init(fmt); + var it: FormatTag.Tokenizer = .init(expanded); while (it.next()) |token| { buf[index] = token; index += 1; @@ -230,8 +250,10 @@ pub fn format(self: DateTime, comptime fmt: []const u8, writer: *std.Io.Writer) .WW => try writer.print("{:0>2}", .{self.isoWeek().week}), .gg => try writer.print("{d:0>2}", .{@as(u7, @intCast(@mod(self.localeWeek().year, 100)))}), .gggg => try printYear(writer, self.localeWeek().year), + .ggggg => try printPaddedYear(writer, self.localeWeek().year, 5), .GG => try writer.print("{d:0>2}", .{@as(u7, @intCast(@mod(self.isoWeek().year, 100)))}), .GGGG => try printYear(writer, self.isoWeek().year), + .GGGGG => try printPaddedYear(writer, self.isoWeek().year, 5), // @mod rather than @rem, so a year either side of the // epoch lands in 0-99 rather than going negative, and the @@ -239,8 +261,21 @@ pub fn format(self: DateTime, comptime fmt: []const u8, writer: *std.Io.Writer) // is the inverse of the parse side, which reads two // digits as 2000-2099. .YY => try writer.print("{d:0>2}", .{@as(u7, @intCast(@mod(self.year, 100)))}), - .YYY => try writer.print("{d}", .{self.year}), + .Y, .y, .yy, .yyy, .yyyy => try writer.print("{d}", .{self.year}), + .yo => try print.ordinal(writer, @as(u32, @intCast(@max(self.year, 0)))), .YYYY => try printYear(writer, self.year), + .YYYYY => try printPaddedYear(writer, self.year, 5), + .YYYYYY => { + // Always signed, which is what makes it the expanded + // form rather than a wider `YYYY`. + try writer.writeAll(if (self.year < 0) "-" else "+"); + try writer.print("{d:0>6}", .{@abs(self.year)}); + }, + + // Every spelling but the longest abbreviates, which is + // moment.js's arrangement and not an oversight. + .N, .NN, .NNN, .NNNNN => try writer.writeAll(if (self.year < 1) "BC" else "AD"), + .NNNN => try writer.writeAll(if (self.year < 1) "Before Christ" else "Anno Domini"), .A => try writeTwelveHour(self.hour, .upper, writer), .a => try writeTwelveHour(self.hour, .lower, writer), @@ -300,16 +335,20 @@ pub fn format(self: DateTime, comptime fmt: []const u8, writer: *std.Io.Writer) .Z => try print.offset(writer, self.offset, .colon), .ZZ => try print.offset(writer, self.offset, .none), - // .x => try writer.print("{}", .{self.toUnixMilli()}), - // .X => try writer.print("{}", .{self.toUnix()}), - }, - .char => |c| switch (c) { - ',', ' ', ':', '-', '.', 'T', 'W' => try writer.writeAll(&.{c}), - else => @compileError(std.fmt.comptimePrint( - "DateTime: unsupported literal character '{c}' in format string", - .{c}, - )), + // The hour is unpadded and everything after it is, so + // these are not the same as writing the parts separately. + .Hmm => try writer.print("{d}{d:0>2}", .{ self.hour, self.minute }), + .Hmmss => try writer.print("{d}{d:0>2}{d:0>2}", .{ self.hour, self.minute, self.second }), + .hmm => try writer.print("{d}{d:0>2}", .{ wrap(self.hour, 12), self.minute }), + .hmmss => try writer.print("{d}{d:0>2}{d:0>2}", .{ wrap(self.hour, 12), self.minute, self.second }), + + .X => try writer.print("{d}", .{@divFloor(self.toInstant().timestamp, std.time.ns_per_s)}), + .x => try writer.print("{d}", .{@divFloor(self.toInstant().timestamp, std.time.ns_per_ms)}), }, + // Anything that is not a sequence is copied through, which + // is what moment.js does and what makes `YYYY/MM/DD` and + // `[today is] dddd` mean what they look like. + .literal => |text| try writer.writeAll(text), } } @@ -425,16 +464,34 @@ test parse { /// `error.IllegalToken` it raises there surfaces as a compile error and /// never reaches a caller. pub fn parseRelativeTo(comptime format_string: []const u8, relative_to: DateTime, value: []const u8) ParseError!ParseResult { + const expanded = comptime formatsequence.expandLocalized(format_string); + const tokens: []const FormatTag.Tokenizer.Token = comptime tokens: { @setEvalBranchQuota(200000); var count = 0; { - var it: FormatTag.Tokenizer = .init(format_string); + var it: FormatTag.Tokenizer = .init(expanded); while (it.next()) |token| { switch (token) { .tag => |tag| switch (tag) { .Q, .Qo, + .yo, + .N, + .NN, + .NNN, + .NNNN, + .NNNNN, + .YYYYY, + .YYYYYY, + .Hmm, + .Hmmss, + .hmm, + .hmmss, + .X, + .x, + .ggggg, + .GGGGG, .w, .wo, .ww, @@ -448,7 +505,7 @@ pub fn parseRelativeTo(comptime format_string: []const u8, relative_to: DateTime => return error.IllegalToken, else => {}, }, - .char => {}, + .literal => {}, } count += 1; } @@ -456,7 +513,7 @@ pub fn parseRelativeTo(comptime format_string: []const u8, relative_to: DateTime var tokens: [count]FormatTag.Tokenizer.Token = undefined; var index = 0; { - var it: FormatTag.Tokenizer = .init(format_string); + var it: FormatTag.Tokenizer = .init(expanded); while (it.next()) |token| { tokens[index] = token; index += 1; @@ -490,7 +547,7 @@ pub fn parseRelativeTo(comptime format_string: []const u8, relative_to: DateTime datetime.year = @as(Year, @intCast(read.digits(year))) + 2000; left = left[year.len..]; }, - .YYYY, .YYY => { + .YYYY, .Y, .y, .yy, .yyy, .yyyy => { datetime.year = year: { const str = read.int(left, 4); if (str.len == 0) return error.ParseError; @@ -803,6 +860,22 @@ pub fn parseRelativeTo(comptime format_string: []const u8, relative_to: DateTime }, .Q, .Qo, + .yo, + .N, + .NN, + .NNN, + .NNNN, + .NNNNN, + .YYYYY, + .YYYYYY, + .Hmm, + .Hmmss, + .hmm, + .hmmss, + .X, + .x, + .ggggg, + .GGGGG, .w, .wo, .ww, @@ -819,21 +892,13 @@ pub fn parseRelativeTo(comptime format_string: []const u8, relative_to: DateTime // else => {}, } }, - .char => |char| { - switch (char) { - ',', - ' ', - ':', - '-', - '.', - 'T', - 'W', - => { - if (left[0] != char) return error.ParseError; - left = left[1..]; - }, - else => return error.ParseError, - } + // A literal has to be there, exactly, and is then stepped + // over. Nothing is skipped on its behalf: a format string + // that says a space means a space. + .literal => |text| { + if (left.len < text.len) return error.ParseError; + if (!std.mem.eql(u8, left[0..text.len], text)) return error.ParseError; + left = left[text.len..]; }, } } @@ -900,6 +965,44 @@ test asDate { ); } +/// Returns the instant this reading names, by taking its offset off it. +/// +/// This is the inverse of `Instant.asDateTime`, and is what the `X` and +/// `x` sequences are written from. A wall-clock reading plus an offset +/// names exactly one instant, so unlike `TimeZone.resolve` there is +/// nothing here that can be ambiguous or missing. +pub fn toInstant(self: DateTime) Instant { + const seconds = @as(i64, self.asDate().toDaysSinceStartOfEra()) * std.time.s_per_day + + @as(i64, self.hour) * std.time.s_per_hour + + @as(i64, self.minute) * std.time.s_per_min + + @as(i64, self.second) - + self.offset; + + return .{ + .timestamp = @as(i128, seconds) * std.time.ns_per_s + self.nanosecond, + }; +} + +test toInstant { + // The epoch, and the same instant written against a zone five hours + // behind it. + const utc_epoch: DateTime = .{ .year = 1970, .month = .Jan, .day = 1 }; + try std.testing.expectEqual(@as(i128, 0), utc_epoch.toInstant().timestamp); + + const shifted: DateTime = .{ + .year = 1969, + .month = .Dec, + .day = 31, + .hour = 19, + .offset = -5 * std.time.s_per_hour, + }; + try std.testing.expectEqual(@as(i128, 0), shifted.toInstant().timestamp); + + // It undoes `Instant.asDateTime`. + const instant: Instant = .fromNanoTimeStamp(1710513005123456789); + try std.testing.expectEqual(instant.timestamp, instant.asDateTime().toInstant().timestamp); +} + /// Returns the ISO 8601 week this date falls in, and the year that week /// belongs to. See `Date.isoWeek`, which this defers to. The `W` and `GG` /// format sequences write these. @@ -1592,7 +1695,10 @@ test "the sequences that differ only in padding" { // old day-of-year-over-seven arithmetic got wrong: it gave 0. .{ .fmt = "w-ww", .expected = "1-01" }, .{ .fmt = "DDD-DDDD", .expected = "3-003" }, - .{ .fmt = "YY-YYY-YYYY", .expected = "24-2024-2024" }, + .{ .fmt = "YY-YYYY", .expected = "24-2024" }, + // `YYY` is not a sequence: it reads as `YY` and then `Y`, which + // is what moment.js makes of it too. + .{ .fmt = "YYY", .expected = "242024" }, }; inline for (cases) |case| { diff --git a/src/formatsequence.zig b/src/formatsequence.zig index b863b06..abe2ff3 100644 --- a/src/formatsequence.zig +++ b/src/formatsequence.zig @@ -16,6 +16,115 @@ const std = @import("std"); /// One sequence of a format string. The field names are the sequences /// themselves, which is what `Tokenizer` matches against. +/// The localized format sequences, which stand for a whole format string +/// rather than for one value, paired with what each stands for. +/// +/// These are the `en` locale's, which is the only locale there is here and +/// is moment.js's default. The lower-case spellings are the upper-case +/// ones with the padding taken off the month, day and weekday, which is +/// how moment derives them rather than listing them. +/// +/// Longest first, because `LLLL` has to be recognized before `LLL`. +const localized = [_]struct { sequence: []const u8, expansion: []const u8 }{ + .{ .sequence = "LTS", .expansion = "h:mm:ss A" }, + .{ .sequence = "LT", .expansion = "h:mm A" }, + .{ .sequence = "LLLL", .expansion = "dddd, MMMM D, YYYY h:mm A" }, + .{ .sequence = "LLL", .expansion = "MMMM D, YYYY h:mm A" }, + .{ .sequence = "LL", .expansion = "MMMM D, YYYY" }, + .{ .sequence = "L", .expansion = "MM/DD/YYYY" }, + .{ .sequence = "llll", .expansion = "ddd, MMM D, YYYY h:mm A" }, + .{ .sequence = "lll", .expansion = "MMM D, YYYY h:mm A" }, + .{ .sequence = "ll", .expansion = "MMM D, YYYY" }, + .{ .sequence = "l", .expansion = "M/D/YYYY" }, +}; + +/// Replaces every localized sequence in `format_string` with what it +/// stands for, leaving everything else alone. +/// +/// This runs before tokenizing because a localized sequence is not a value +/// but a shorthand for other sequences, so `LT` has to become `h:mm A` +/// before anything tries to read an `L`. Bracketed text and anything after +/// a backslash are stepped over rather than expanded, so `[LT]` stays the +/// two letters it looks like. +/// +/// The replacement runs until nothing changes, bounded so that a locale +/// whose expansion contained its own sequence could not spin. moment.js +/// bounds it the same way and for the same reason. +pub fn expandLocalized(comptime format_string: []const u8) []const u8 { + comptime { + // Every character of every pass is a backwards branch, and the + // default allowance is a thousand. Set here rather than left to + // the caller so that this is usable on its own. + @setEvalBranchQuota(100000); + + var current: []const u8 = format_string; + + for (0..6) |_| { + var out: []const u8 = ""; + var index: usize = 0; + var changed = false; + + scan: while (index < current.len) { + const rest = current[index..]; + + if (rest[0] == '[') { + if (std.mem.indexOfAny(u8, rest[1..], "[]")) |offset| { + if (rest[1 + offset] == ']') { + out = out ++ rest[0 .. offset + 2]; + index += offset + 2; + continue :scan; + } + } + } + + if (rest[0] == '\\' and rest.len > 1) { + out = out ++ rest[0..2]; + index += 2; + continue :scan; + } + + for (localized) |entry| { + if (std.mem.startsWith(u8, rest, entry.sequence)) { + out = out ++ entry.expansion; + index += entry.sequence.len; + changed = true; + continue :scan; + } + } + + out = out ++ rest[0..1]; + index += 1; + } + + if (!changed) return current; + current = out; + } + + return current; + } +} + +test expandLocalized { + try std.testing.expectEqualStrings("MM/DD/YYYY", comptime expandLocalized("L")); + try std.testing.expectEqualStrings("h:mm A", comptime expandLocalized("LT")); + try std.testing.expectEqualStrings("M/D/YYYY", comptime expandLocalized("l")); + + // The longest spelling wins, so five Ls are the four letter one and + // then the one letter one. + try std.testing.expectEqualStrings( + "dddd, MMMM D, YYYY h:mm AMM/DD/YYYY", + comptime expandLocalized("LLLLL"), + ); + + // Bracketed text is not a sequence, and neither is anything a + // backslash claimed. + try std.testing.expectEqualStrings("[LT]", comptime expandLocalized("[LT]")); + try std.testing.expectEqualStrings("\\LT", comptime expandLocalized("\\LT")); + + // Anything with no localized sequence in it comes back unchanged. + try std.testing.expectEqualStrings("YYYY-MM-DD", comptime expandLocalized("YYYY-MM-DD")); +} + pub const FormatTag = enum { /// 1 2 ... 11 12 (month, numeric) M, @@ -72,15 +181,58 @@ pub const FormatTag = enum { gg, /// 1970 1971 ... 2029 2030 (week-numbering year) gggg, + /// 02024 (week-numbering year, zero padded to five digits) + ggggg, /// 70 71 ... 29 30 (ISO week-numbering year, last two digits) /// /// The year the week written by `W` belongs to. GG, /// 1970 1971 ... 2029 2030 (ISO week-numbering year) GGGG, - YY, // 70 71 ... 29 30 (year, last two digits only) - YYY, // 1 2 ... 1970 1971 ... 2029 2030 (year) - YYYY, // 0001 0002 ... 1970 1971 ... 2029 2030 (year, zero padded to 4 digits) + /// 02024 (ISO week-numbering year, zero padded to five digits) + GGGGG, + /// 70 71 ... 29 30 (year, last two digits only) + YY, + /// 0001 0002 ... 1970 1971 ... 2029 2030 (year, zero padded to four + /// digits, with a leading minus before the common era) + YYYY, + /// 02024 (year, zero padded to five digits) + YYYYY, + /// +002024 (year, always signed, zero padded to six digits) + /// + /// This is ISO 8601's expanded year, which the standard allows only by + /// prior agreement between the parties exchanging the data; `iso8601` + /// deliberately does not parse it. + YYYYYY, + /// 1 2 ... 1970 1971 ... 2029 2030 (year, unpadded) + /// + /// Note that `YYY` is not a sequence: it reads as `YY` followed by + /// this, which is what moment.js makes of it too. + Y, + /// 1 2 ... 1970 1971 ... 2029 2030 (era year, unpadded) + /// + /// The year counted within its era, which for the common era is the + /// year itself. `yy`, `yyy` and `yyyy` all mean the same thing, as + /// they do in moment.js. + y, + /// 1st 2nd ... 2029th 2030th (era year, ordinal) + yo, + /// Same as `y`. + yy, + /// Same as `y`. + yyy, + /// Same as `y`. + yyyy, + /// AD (era, abbreviated) + N, + /// Same as `N`. + NN, + /// Same as `N`. + NNN, + /// Anno Domini (era, in full) + NNNN, + /// Same as `N`. + NNNNN, // @"±YYYY", // /// BCE/CE (BC and AD will be accepted for parsing, but not emitted on // /// formatting). @@ -117,6 +269,21 @@ pub const FormatTag = enum { SSSSSSS, // 0000000 00000000 ... 9999998 9999999 (hundreds of nanoseconds) SSSSSSSS, // 00000000 000000000 ... 99999998 99999999 (tens of nanoseconds) SSSSSSSSS, // 000000000 000000000 ... 999999998 999999999 (nanoseconds) + /// 1430 (hour and minute, run together, hour unpadded) + /// + /// One sequence rather than `H` beside `mm`, which is what moment.js + /// makes of these four spellings too. + Hmm, + /// 143005 (hour, minute and second, run together) + Hmmss, + /// 230 (hour on the 12 hour clock and minute, run together) + hmm, + /// 23005 (hour on the 12 hour clock, minute and second) + hmmss, + /// 1710513005 (seconds since the Unix epoch) + X, + /// 1710513005000 (milliseconds since the Unix epoch) + x, // z, // EST CST ... MST PST /// -07:00 -06:00 ... +06:00 +07:00 (offset from UTC). Note that this /// makes a bare `Z` in a format string an offset rather than the @@ -168,9 +335,13 @@ pub const FormatTag = enum { format_string: []const u8, /// What the tokenizer produces: either a recognized sequence or a - /// literal character to be copied through as-is. + /// run of characters to be copied through as-is. + /// + /// A literal is a slice rather than a byte because bracketed text + /// arrives all at once, and because an escape can produce nothing + /// at all; see `next`. pub const Token = union(enum) { - char: u8, + literal: []const u8, tag: FormatTag, }; @@ -188,31 +359,83 @@ pub const FormatTag = enum { try std.testing.expectEqual(@as(?Token, null), it.next()); } + /// Returns the length of the sequence beginning at `index`, or + /// null when nothing there is one. + fn tagAt(self: Tokenizer, index: usize) ?FormatTag { + var found: ?FormatTag = null; + var length: usize = 0; + inline for (@typeInfo(FormatTag).@"enum".fields) |field| { + if (field.name.len > length and + index + field.name.len <= self.format_string.len and + std.mem.eql(u8, field.name, self.format_string[index..][0..field.name.len])) + { + found = @enumFromInt(field.value); + length = field.name.len; + } + } + return found; + } + /// Returns the next token, or null when the format string is /// exhausted. + /// + /// Three things can appear. Text in square brackets is a literal, + /// which is how a format string writes something that would + /// otherwise be read as a sequence. A backslash makes a literal of + /// whatever follows it, sequence or single character. Anything + /// else is the longest sequence that matches, or one character + /// passed through when none does. + /// + /// The corners are moment.js's, and are followed deliberately + /// rather than tidied. A `[` with no `]` after it is a literal + /// bracket rather than an error, and so is a `[` that would have + /// to nest. A backslash before another backslash yields nothing + /// at all, because moment strips every backslash out of the run it + /// matched, and a trailing backslash likewise. See + /// `tools/oracle.js`, which checks all of it. pub fn next(self: *Tokenizer) ?Token { if (self.index >= self.format_string.len) return null; - var tag_: ?FormatTag = null; - var tag_len: usize = 0; - inline for (@typeInfo(FormatTag).@"enum".fields) |field| { - if (field.name.len > tag_len and - self.index + field.name.len <= self.format_string.len and - std.mem.eql(u8, field.name, self.format_string[self.index..][0..field.name.len])) - { - tag_ = @enumFromInt(field.value); - tag_len = field.name.len; + + const rest = self.format_string[self.index..]; + + if (rest[0] == '[') { + // The closing bracket has to come before any second + // opening one, which is what makes `[a[b]` a literal + // bracket followed by `a` and then the literal `b`. + if (std.mem.indexOfAny(u8, rest[1..], "[]")) |offset| { + if (rest[1 + offset] == ']') { + defer self.index += offset + 2; + return .{ .literal = rest[1..][0..offset] }; + } } + defer self.index += 1; + return .{ .literal = rest[0..1] }; } - if (tag_) |tag| { + + if (rest[0] == '\\') { + // A backslash with nothing after it, and a backslash + // before another backslash, both come to nothing. + if (rest.len == 1) { + defer self.index += 1; + return .{ .literal = rest[0..0] }; + } + if (rest[1] == '\\') { + defer self.index += 2; + return .{ .literal = rest[0..0] }; + } + + const length = if (self.tagAt(self.index + 1)) |tag| @tagName(tag).len else 1; + defer self.index += 1 + length; + return .{ .literal = rest[1..][0..length] }; + } + + if (self.tagAt(self.index)) |tag| { defer self.index += @tagName(tag).len; - return .{ - .tag = tag, - }; + return .{ .tag = tag }; } + defer self.index += 1; - return .{ - .char = self.format_string[self.index], - }; + return .{ .literal = rest[0..1] }; } test next { @@ -221,9 +444,26 @@ pub const FormatTag = enum { // back as a literal. var it: Tokenizer = .init("MM-D"); try std.testing.expectEqual(FormatTag.MM, it.next().?.tag); - try std.testing.expectEqual(@as(u8, '-'), it.next().?.char); + try std.testing.expectEqualStrings("-", it.next().?.literal); try std.testing.expectEqual(FormatTag.D, it.next().?.tag); try std.testing.expectEqual(@as(?Token, null), it.next()); + + // Brackets make a literal of what would otherwise be read as + // a sequence. + var bracketed: Tokenizer = .init("[Y]YYYY"); + try std.testing.expectEqualStrings("Y", bracketed.next().?.literal); + try std.testing.expectEqual(FormatTag.YYYY, bracketed.next().?.tag); + + // A bracket that never closes is just a bracket. + var unclosed: Tokenizer = .init("[MM"); + try std.testing.expectEqualStrings("[", unclosed.next().?.literal); + try std.testing.expectEqual(FormatTag.MM, unclosed.next().?.tag); + + // A backslash takes the whole sequence after it, not one + // character of it. + var escaped: Tokenizer = .init("\\MMD"); + try std.testing.expectEqualStrings("MM", escaped.next().?.literal); + try std.testing.expectEqual(FormatTag.D, escaped.next().?.tag); } }; }; diff --git a/tools/oracle_dump.zig b/tools/oracle_dump.zig index ce906e2..5c7c634 100644 --- a/tools/oracle_dump.zig +++ b/tools/oracle_dump.zig @@ -57,23 +57,46 @@ const sweep_step = std.time.ms_per_day; /// actually writes. const formats = [_][]const u8{ // Every sequence on its own. - "M", "Mo", "MM", "MMM", - "MMMM", "Q", "Qo", "D", - "Do", "DD", "DDD", "DDDo", - "DDDD", "d", "do", "dd", - "ddd", "dddd", "e", "E", - "w", "wo", "ww", "W", - "Wo", "WW", "gg", "gggg", - "GG", "GGGG", "YY", "YYYY", - "A", "a", "H", "HH", - "h", "hh", "k", "kk", - "m", "mm", "s", "ss", - "S", "SS", "SSS", "Z", - "ZZ", + "M", "Mo", "MM", "MMM", + "MMMM", "Q", "Qo", "D", + "Do", "DD", "DDD", "DDDo", + "DDDD", "d", "do", "dd", + "ddd", "dddd", "e", "E", + "w", "wo", "ww", "W", + "Wo", "WW", "gg", "gggg", + "ggggg", "GG", "GGGG", "GGGGG", + "Y", "YY", "YYYY", "YYYYY", + "YYYYYY", "y", "yo", "yy", + "yyy", "yyyy", "N", "NN", + "NNN", "NNNN", "NNNNN", "A", + "a", "H", "HH", "h", + "hh", "k", "kk", "m", + "mm", "s", "ss", "S", + "SS", "SSS", "Z", "ZZ", + "X", "x", "Hmm", "Hmmss", + "hmm", "hmmss", + // Sequences that only differ from their parts when run together. + "YYY", "H mm", + "h mm ss", + // Literals, escaping, and the corners of both. + "YYYY/MM/DD", "[abc]", "[Y]YYYY", + "a[bc]d", "[]", "[[]", "[abc", + "abc]", "[a[b]", "q", "%", + "#$@!", "YYYY[T]HH", "[today is] dddd", // The shapes a caller writes. - "YYYY-MM-DD", "YYYY-MM-DDTHH:mm:ss", "HH:mm", - "h:mm a", "dddd, D MMMM YYYY", "ddd, DD MMM YYYY HH:mm:ss ZZ", "MMM D", - "Do MMMM", "YYYY-MM-DDTHH:mm:ssZ", "GGGG-WW-E", "gggg-ww-e", + "YYYY-MM-DD", + "YYYY-MM-DDTHH:mm:ss", "HH:mm", "h:mm a", "dddd, D MMMM YYYY", + "ddd, DD MMM YYYY HH:mm:ss ZZ", "MMM D", "Do MMMM", "YYYY-MM-DDTHH:mm:ssZ", + "GGGG-[W]WW-E", "gggg-[W]ww-e", + // The localized sequences, which stand for a whole format string. + "L", "LL", + "LLL", "LLLL", "LT", "LTS", + "l", "ll", "lll", "llll", + "LLLLL", "L LT", "[L] L", "hello", + // Backslash escaping, including the corners where moment drops the + // whole run it matched. + "\\Y", "\\\\Y", "YYYY\\-MM", "\\[abc\\]", + "\\MMD", "\\", }; pub fn main(init: std.process.Init) !void { -- knotmirror 0.0.1