// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! EXSLT's [`dates-and-times`][] module: the calendar functions a stylesheet //! reaches for. //! //! [`dates-and-times`]: http://exslt.org/date/index.html //! //! The arithmetic and the calendar itself are [zig-datetime][]'s, which is //! where they belong -- a calendar is the kind of thing that is wrong in the //! same way in every project that reimplements it. What is here is the part //! that is XSLT's rather than the calendar's: XML Schema's eight //! right-truncated date types, the rule that decides which of them an answer //! is written in, and the year numbering. //! //! [zig-datetime]: https://git.jcollie.dev/jeff/zig-datetime //! //! **XML Schema has no year zero.** `-0001` is 1 BCE and the year after it is //! `0001`, where the calendar underneath numbers years astronomically and has //! a year 0 like any other. So a year is converted on the way in and on the //! way out, and everything in between -- including whether a year is a leap //! year -- is asked of the astronomical one. That is not a detail: it is why //! `date:add('-0001-12-31T23:59:59', 'PT1S')` is `0001-01-01T00:00:00` and //! why `date:leap-year('-0001')` is true. const std = @import("std"); const datetime = @import("datetime"); const zxpath = @import("zxpath"); const Value = zxpath.value.Value; const value = zxpath.value; const DateTime = datetime.DateTime; const Duration = datetime.Duration; pub const ns = "http://exslt.org/dates-and-times"; pub const Error = error{WrongArgumentCount} || std.mem.Allocator.Error; /// Which of XML Schema's date and time types a value is. /// /// The numbers are libxslt's, and they are a bit set rather than a sequence: /// a type *contains* the parts it is made of, so `date` is year, month and /// day together and `date_time` is that plus a time. That is what makes /// "does this type have a year in it" a mask and "is this type less specific /// than that one" a comparison. pub const Kind = enum(u4) { time = 1, g_day = 2, g_month = 4, g_month_day = 4 | 2, g_year = 8, g_year_month = 8 | 4, date = 8 | 4 | 2, date_time = 8 | 4 | 2 | 1, /// Whether this type carries all the parts of `part`. pub fn has(self: Kind, part: Kind) bool { const bits = @backingInt(part); return @backingInt(self) & bits == bits; } }; /// A date, a time, or as much of either as was written. pub const Stamp = struct { kind: Kind, /// The fields, with the year numbered astronomically rather than as XML /// Schema numbers it. `schemaYear` converts back. dt: DateTime, /// Whether the text carried a timezone. `dt.offset` is zero either way, /// so this is the only thing that distinguishes a local time from one /// that ended in `Z`. has_offset: bool, /// The fraction of a second as it was written, to whatever precision /// that was. /// /// `dt.nanosecond` holds the same thing rounded to a nanosecond, which is /// what the arithmetic and the output use -- but `date:second-in-minute` /// returns a *number*, and libxslt keeps its seconds as a double, so /// `15:55:59.99999999999` answers with all eleven digits while writing /// only nine. Keeping both is the only way to agree with it twice. fraction: f64 = 0, /// The year as XML Schema writes it, which has no zero. pub fn schemaYear(self: Stamp) i64 { return if (self.dt.year <= 0) @as(i64, self.dt.year) - 1 else self.dt.year; } }; // -- parsing ----------------------------------------------------------------- /// Reads one of XML Schema's date or time types, or null when the whole of /// `text` is not exactly one of them. /// /// The decision tree is libxslt's, and the order matters: `10:30:00` has to /// be tried as a time before it is tried as a year, because a year is four /// digits and `10:3` is not. pub fn parse(text: []const u8) ?Stamp { var c: Cursor = .{ .text = text }; var s: Stamp = .{ .kind = .date_time, .dt = .{}, .has_offset = false }; // `--` begins the three types with no year: gMonthDay, gMonth, gDay. if (std.mem.startsWith(u8, text, "--")) { c.index = 2; if (c.eat('-')) { s.dt.day = @intCast(c.twoDigits(1, 31) orelse return null); return finish(&c, &s, .g_day); } s.dt.month = @fromBackingInt(@intCast(c.twoDigits(1, 12) orelse return null)); if (!c.eat('-')) return null; // `--MM--` is a gMonth; `--MM-DD` is a gMonthDay. The second hyphen // is XML Schema 1.0's spelling, and libxslt still requires it. if (c.eat('-')) return finish(&c, &s, .g_month); s.dt.day = @intCast(c.twoDigits(1, 31) orelse return null); return finish(&c, &s, .g_month_day); } // A bare time, tried first because nothing else starts with two digits // and a colon. { var t = c; if (readTime(&t, &s)) { if (finish(&t, &s, .time)) |done| return done; } s.dt = .{}; s.fraction = 0; } if (!readYear(&c, &s)) return null; if (finish(&c, &s, .g_year)) |done| return done; if (!c.eat('-')) return null; s.dt.month = @fromBackingInt(@intCast(c.twoDigits(1, 12) orelse return null)); if (finish(&c, &s, .g_year_month)) |done| return done; if (!c.eat('-')) return null; s.dt.day = @intCast(c.twoDigits(1, 31) orelse return null); if (s.dt.day > s.dt.month.lastDay(s.dt.year)) return null; if (finish(&c, &s, .date)) |done| return done; if (!c.eat('T')) return null; if (!readTime(&c, &s)) return null; return finish(&c, &s, .date_time); } /// Reads the timezone, if any, and accepts the value only if the text ends /// there. This is libxslt's `RETURN_TYPE_IF_VALID`: every level of the tree /// asks whether the value stops here, and the answer is yes only when what /// follows is a timezone and nothing else. fn finish(c: *Cursor, s: *Stamp, kind: Kind) ?Stamp { if (!c.done() and c.peek() != 'Z' and c.peek() != '+' and c.peek() != '-') return null; var probe = c.*; var result = s.*; if (!readTimeZone(&probe, &result)) return null; if (!probe.done()) return null; result.kind = kind; // The weekday is deliberately left alone. A gMonthDay may name a day its // default month does not have -- libxslt accepts `--02-30`, since the // type names no year to decide it against -- and asking the calendar for // the weekday of a date like that is asking it something it has no answer // to. Nothing needs the weekday except the functions that require a whole // date, and those compute it from one. return result; } fn readYear(c: *Cursor, s: *Stamp) bool { const negative = c.eat('-'); const start = c.index; var year: i64 = 0; while (!c.done() and std.ascii.isDigit(c.peek())) { year = year * 10 + (c.peek() - '0'); if (year > std.math.maxInt(i32)) return false; c.index += 1; } const digits = c.index - start; // Four digits at least, and no leading zero past four: `0001` and `10000` // are years, `001` and `010000` are not. if (digits < 4) return false; if (digits > 4 and c.text[start] == '0') return false; // There is no year zero to write. if (year == 0) return false; s.dt.year = @intCast(if (negative) 1 - year else year); return true; } fn readTime(c: *Cursor, s: *Stamp) bool { const hour = c.twoDigits(0, 23) orelse return false; if (!c.eat(':')) return false; const minute = c.twoDigits(0, 59) orelse return false; if (!c.eat(':')) return false; const second = c.twoDigits(0, 59) orelse return false; var nanosecond: u64 = 0; var fraction: f64 = 0; if (c.eat('.')) { const start = c.index; var scale: u64 = 100_000_000; while (!c.done() and std.ascii.isDigit(c.peek())) { if (scale != 0) { nanosecond += @as(u64, c.peek() - '0') * scale; scale /= 10; } c.index += 1; } if (c.index == start) return false; // Parsed again as a double, at whatever precision was written, for // `date:second-in-minute`. A malformed fraction cannot reach here. var buf: [32]u8 = undefined; const digits = c.text[start..c.index]; const kept = @min(digits.len, buf.len - 2); buf[0] = '.'; @memcpy(buf[1 .. 1 + kept], digits[0..kept]); fraction = std.fmt.parseFloat(f64, buf[0 .. 1 + kept]) catch 0; } s.dt.hour = @intCast(hour); s.dt.minute = @intCast(minute); s.dt.second = @intCast(second); s.dt.nanosecond = @intCast(nanosecond); s.fraction = fraction; return true; } fn readTimeZone(c: *Cursor, s: *Stamp) bool { if (c.done()) { s.has_offset = false; return true; } if (c.eat('Z')) { s.has_offset = true; s.dt.offset = 0; return true; } const negative = if (c.eat('-')) true else if (c.eat('+')) false else return false; const hour = c.twoDigits(0, 23) orelse return false; if (!c.eat(':')) return false; const minute = c.twoDigits(0, 59) orelse return false; const minutes: i32 = @as(i32, hour) * 60 + minute; s.has_offset = true; s.dt.offset = (if (negative) -minutes else minutes) * 60; return true; } const Cursor = struct { text: []const u8, index: usize = 0, fn done(self: Cursor) bool { return self.index >= self.text.len; } fn peek(self: Cursor) u8 { return self.text[self.index]; } fn eat(self: *Cursor, char: u8) bool { if (self.done() or self.peek() != char) return false; self.index += 1; return true; } /// Exactly two digits, and only if the value they spell is in range. fn twoDigits(self: *Cursor, low: u8, high: u8) ?u8 { if (self.index + 2 > self.text.len) return null; const a = self.text[self.index]; const b = self.text[self.index + 1]; if (!std.ascii.isDigit(a) or !std.ascii.isDigit(b)) return null; const v = (a - '0') * 10 + (b - '0'); if (v < low or v > high) return null; self.index += 2; return v; } }; // -- writing ----------------------------------------------------------------- /// Writes a value in the syntax of its own type. /// /// A `date_time` gets a timezone whatever `has_offset` says, which is /// libxslt's behaviour and not the other formatters': `date`, `time` and the /// `g*` types write one only when there was one to write. It means a local /// dateTime comes back with a `Z` on it that it never had. That is a bug, it /// is the oracle's, and reproducing it is the difference between agreeing /// with every other processor and disagreeing with all of them. pub fn write(w: *std.Io.Writer, s: Stamp) std.Io.Writer.Error!void { if (s.kind.has(.g_year)) { try writeYear(w, s); if (s.kind.has(.g_month)) { try w.print("-{d:0>2}", .{@backingInt(s.dt.month)}); } if (s.kind.has(.g_day)) { try w.print("-{d:0>2}", .{s.dt.day}); } } else if (s.kind == .g_month or s.kind == .g_month_day) { try w.print("--{d:0>2}", .{@backingInt(s.dt.month)}); if (s.kind == .g_month) { try w.writeAll("--"); } else { try w.print("-{d:0>2}", .{s.dt.day}); } } else if (s.kind == .g_day) { try w.print("---{d:0>2}", .{s.dt.day}); } if (s.kind.has(.time)) { if (s.kind == .date_time) try w.writeByte('T'); try writeTime(w, s); // The one place the offset is not conditional. if (s.kind == .date_time) return writeOffset(w, s.dt.offset); } if (s.has_offset or s.dt.offset != 0) try writeOffset(w, s.dt.offset); } fn writeYear(w: *std.Io.Writer, s: Stamp) std.Io.Writer.Error!void { const year = s.schemaYear(); if (year < 0) try w.writeByte('-'); try w.print("{d:0>4}", .{@abs(year)}); } fn writeTime(w: *std.Io.Writer, s: Stamp) std.Io.Writer.Error!void { try w.print("{d:0>2}:{d:0>2}:{d:0>2}", .{ s.dt.hour, s.dt.minute, s.dt.second }); try writeFraction(w, s.dt.nanosecond); } /// The fraction of a second, with its trailing zeroes dropped, or nothing at /// all when there is no fraction. fn writeFraction(w: *std.Io.Writer, nanosecond: u64) std.Io.Writer.Error!void { if (nanosecond == 0) return; var digits: [9]u8 = undefined; _ = std.fmt.printInt(&digits, nanosecond, 10, .lower, .{ .fill = '0', .width = 9 }); var len: usize = digits.len; while (len > 1 and digits[len - 1] == '0') len -= 1; try w.print(".{s}", .{digits[0..len]}); } fn writeOffset(w: *std.Io.Writer, offset: i32) std.Io.Writer.Error!void { if (offset == 0) return w.writeByte('Z'); const minutes: u32 = @abs(@divTrunc(offset, 60)); try w.print("{c}{d:0>2}:{d:0>2}", .{ @as(u8, if (offset < 0) '-' else '+'), minutes / 60, minutes % 60, }); } /// The same, into a string the caller owns. pub fn toOwnedString(gpa: std.mem.Allocator, s: Stamp) std.mem.Allocator.Error![]u8 { var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); write(&out.writer, s) catch return error.OutOfMemory; return out.toOwnedSlice(); } // -- functions --------------------------------------------------------------- const Function = enum { @"date-time", date, time, year, @"leap-year", @"month-in-year", @"month-name", @"month-abbreviation", @"week-in-year", @"week-in-month", @"day-in-year", @"day-in-month", @"day-of-week-in-month", @"day-in-week", @"day-name", @"day-abbreviation", @"hour-in-day", @"minute-in-hour", @"second-in-minute", add, @"add-duration", sum, difference, duration, seconds, }; const names = std.StaticStringMap(Function).initComptime(.{ .{ "date-time", .@"date-time" }, .{ "date", .date }, .{ "time", .time }, .{ "year", .year }, .{ "leap-year", .@"leap-year" }, .{ "month-in-year", .@"month-in-year" }, .{ "month-name", .@"month-name" }, .{ "month-abbreviation", .@"month-abbreviation" }, .{ "week-in-year", .@"week-in-year" }, .{ "week-in-month", .@"week-in-month" }, .{ "day-in-year", .@"day-in-year" }, .{ "day-in-month", .@"day-in-month" }, .{ "day-of-week-in-month", .@"day-of-week-in-month" }, .{ "day-in-week", .@"day-in-week" }, .{ "day-name", .@"day-name" }, .{ "day-abbreviation", .@"day-abbreviation" }, .{ "hour-in-day", .@"hour-in-day" }, .{ "minute-in-hour", .@"minute-in-hour" }, .{ "second-in-minute", .@"second-in-minute" }, .{ "add", .add }, .{ "add-duration", .@"add-duration" }, .{ "sum", .sum }, .{ "difference", .difference }, .{ "duration", .duration }, .{ "seconds", .seconds }, }); /// True when a function of this name is implemented. pub fn has(local: []const u8) bool { return names.has(local); } /// Calls one of the module's functions, or answers null when this is not one /// of them. /// /// `now` is the current date and time, which the no-argument forms of most of /// these return some part of. It is null when the caller gave the /// transformation no clock to read, and then those forms answer as they do /// for an unreadable date: the empty string, or NaN. pub fn call( gpa: std.mem.Allocator, local: []const u8, args: []const Value, now: ?DateTime, ) Error!?Value { const which = names.get(local) orelse return null; switch (which) { .add => { if (args.len != 2) return error.WrongArgumentCount; return try add(gpa, args[0], args[1]); }, .@"add-duration" => { if (args.len != 2) return error.WrongArgumentCount; const a = try durationArg(gpa, args[0]) orelse return try empty(gpa); const b = try durationArg(gpa, args[1]) orelse return try empty(gpa); const total = addSpans(a, b) orelse return try empty(gpa); return try writeDuration(gpa, total); }, .sum => { if (args.len != 1) return error.WrongArgumentCount; if (args[0] != .node_set) return try empty(gpa); // An empty node-set is no duration rather than a zero one, and // the fold is left to right with `add-duration`'s refusal at each // step -- so a sum that borrows part way through fails even when // the total would not have. if (args[0].node_set.len == 0) return try empty(gpa); var total: Duration = .{}; for (args[0].node_set) |node| { const text = try node.stringValue(gpa); defer gpa.free(text); const parsed = datetime.iso8601.parseDuration(text) catch return try empty(gpa); if (parsed.str.len != text.len) return try empty(gpa); if (parsed.fractional) |unit| if (unit != 'S') return try empty(gpa); total = addSpans(total, normalize(parsed.value)) orelse return try empty(gpa); } return try writeDuration(gpa, total); }, .difference => { if (args.len != 2) return error.WrongArgumentCount; return try difference(gpa, args[0], args[1]); }, .duration => { if (args.len > 1) return error.WrongArgumentCount; const n = if (args.len == 0) @as(f64, 1) else try args[0].toNumber(gpa); if (std.math.isNan(n)) return try empty(gpa); // The days are taken first, and in floating point, so that the // remainder keeps the precision it has: a count of seconds large // enough to need every bit of a double has none left over to // multiply by a thousand million. const days = @floor(n / 86400.0); // A day count that will not fit in a 64-bit integer is no // duration anybody can write, and libxslt refuses it at exactly // this bound. if (@abs(days) >= 9.223372036854775e18) return try empty(gpa); const rest = n - days * 86400.0; var span: Duration = .{ .days = @intFromFloat(days), .nanoseconds = @intFromFloat(@round(rest * 1_000_000_000.0)), }; // Rounding the remainder up can reach a whole day. if (span.nanoseconds >= Duration.nanoseconds_per_day) { span.nanoseconds -= Duration.nanoseconds_per_day; span.days += 1; } return try writeDuration(gpa, span); }, .seconds => { if (args.len > 1) return error.WrongArgumentCount; return .{ .number = try secondsOf(gpa, args, now) }; }, .@"date-time" => { if (args.len != 0) return error.WrongArgumentCount; const dt = now orelse return try empty(gpa); return try string(gpa, .{ .kind = .date_time, .dt = dt, .has_offset = true }); }, // Everything else reads a date and answers some part of it. else => {}, } if (args.len > 1) return error.WrongArgumentCount; const stamp: ?Stamp = if (args.len == 0) if (now) |dt| .{ .kind = .date_time, .dt = dt, .has_offset = true } else null else blk: { const text = try args[0].toString(gpa); defer gpa.free(text); break :blk parse(text); }; // Each function accepts only the types that carry what it answers about, // and each has its own answer for anything else: a number function says // NaN and a string function says nothing at all. const accepted = if (stamp) |s| switch (which) { .year, .@"leap-year" => s.kind.has(.g_year), .@"month-in-year" => s.kind.has(.g_month), .@"month-name", .@"month-abbreviation" => s.kind.has(.g_month), .@"day-in-month" => s.kind.has(.g_day), .@"week-in-year", .@"week-in-month", .@"day-in-year", .@"day-of-week-in-month", .@"day-in-week", .@"day-name", .@"day-abbreviation", .date, => s.kind == .date or s.kind == .date_time, .time, .@"hour-in-day", .@"minute-in-hour", .@"second-in-minute", => s.kind == .time or s.kind == .date_time, else => unreachable, } else false; if (!accepted) return switch (which) { .date, .time, .@"month-name", .@"month-abbreviation", .@"day-name", .@"day-abbreviation" => try empty(gpa), else => .{ .number = std.math.nan(f64) }, }; const s = stamp.?; const as_date: datetime.Date = .{ .year = s.dt.year, .month = s.dt.month, .day = s.dt.day }; return switch (which) { .date => try string(gpa, .{ .kind = .date, .dt = s.dt, .has_offset = s.has_offset }), .time => try string(gpa, .{ .kind = .time, .dt = s.dt, .has_offset = s.has_offset }), .year => .{ .number = @floatFromInt(s.schemaYear()) }, // Leap years are asked of the astronomical year, not the one XML // Schema writes: `-0001` is 1 BCE, which is astronomical year 0, and // year 0 is divisible by 400. .@"leap-year" => .{ .boolean = datetime.leap.is(s.dt.year) }, .@"month-in-year" => .{ .number = @floatFromInt(@backingInt(s.dt.month)) }, .@"month-name" => try Value.ownedString(gpa, monthName(s.dt.month)), .@"month-abbreviation" => try Value.ownedString(gpa, monthName(s.dt.month)[0..3]), .@"week-in-year" => .{ .number = @floatFromInt(as_date.isoWeek().week) }, // Which week of its own month the day falls in, counting from the // first day of the month rather than from a weekday. .@"week-in-month" => .{ .number = @floatFromInt((s.dt.day - 1) / 7 + 1) }, .@"day-in-year" => .{ .number = @floatFromInt(dayInYear(as_date)) }, .@"day-in-month" => .{ .number = @floatFromInt(s.dt.day) }, // How many of this weekday have come round in this month, including // today: the 28th is the fourth Wednesday. .@"day-of-week-in-month" => .{ .number = @floatFromInt((s.dt.day - 1) / 7 + 1) }, // Sunday is 1 here, where the calendar numbers it 0. .@"day-in-week" => .{ .number = @floatFromInt(@backingInt(as_date.dayOfWeek()) + 1) }, .@"day-name" => try Value.ownedString(gpa, dayName(as_date.dayOfWeek())), .@"day-abbreviation" => try Value.ownedString(gpa, dayName(as_date.dayOfWeek())[0..3]), .@"hour-in-day" => .{ .number = @floatFromInt(s.dt.hour) }, .@"minute-in-hour" => .{ .number = @floatFromInt(s.dt.minute) }, .@"second-in-minute" => .{ .number = @as(f64, @floatFromInt(s.dt.second)) + s.fraction }, else => unreachable, }; } fn empty(gpa: std.mem.Allocator) Error!Value { return Value.ownedString(gpa, ""); } fn string(gpa: std.mem.Allocator, s: Stamp) Error!Value { return .{ .string = try toOwnedString(gpa, s) }; } /// EXSLT's reading of a duration: a day is exactly 86400 seconds, the /// sub-day part is folded into days by *floor* so that what is left is in /// `[0, 86400)`, and the sign lives on the months and days. /// /// libxslt normalizes this way as it parses, and it is not a detail: it is /// what makes `date:add-duration('P1D', '-PT24H')` come out as `P0D` rather /// than as a pair of fields that disagree, and what lets `-PT10H` be one /// duration rather than two contradictory halves. The ISO 8601 `Duration` /// underneath deliberately does *not* normalize, because it round-trips what /// was written; this is the other convention, and it belongs here. fn normalize(d: Duration) Duration { const day = Duration.nanoseconds_per_day; const carry = @divFloor(d.nanoseconds, day); return .{ .months = d.months, .days = d.days + @as(i64, @intCast(carry)), .nanoseconds = d.nanoseconds - carry * day, }; } /// Adds two normalized durations, or answers null when the result is one /// nobody can write. /// /// "Nobody can write" is EXSLT's own rule, and it is about borrowing rather /// than about signs: months and days are not commensurable, so a positive /// number of months and a negative number of days is a length of time with /// no answer. `P1M + -P1D` fails for that reason, while `P1M + P1D + -P1D` /// succeeds -- the same three durations, and the order decides. fn addSpans(a: Duration, b: Duration) ?Duration { const day = Duration.nanoseconds_per_day; var r: Duration = .{ .months = a.months + b.months, .days = a.days + b.days, .nanoseconds = a.nanoseconds + b.nanoseconds, }; // Both operands are normalized, so the sum of their sub-day parts is at // most one day over. if (r.nanoseconds >= day) { r.nanoseconds -= day; r.days += 1; } if (r.days >= 0) { if ((r.days > 0 or r.nanoseconds > 0) and r.months < 0) return null; } else { if (r.months > 0) return null; } return r; } /// Writes a normalized duration the way EXSLT does, which is not quite ISO /// 8601's canonical form: no time at all is `P0D` rather than `PT0S`, and the /// sign has to be lifted back out of the days before the magnitudes can be /// written. fn writeDuration(gpa: std.mem.Allocator, span: Duration) Error!Value { const day = Duration.nanoseconds_per_day; if (span.months == 0 and span.days == 0 and span.nanoseconds == 0) { return Value.ownedString(gpa, "P0D"); } var months = span.months; var days = span.days; var nanoseconds = span.nanoseconds; var negative = false; // Undo the normalization: a negative duration is held as a day too far // back plus a positive remainder, and what has to be written is the // magnitude. if (days < 0) { if (nanoseconds != 0) { nanoseconds = day - nanoseconds; days += 1; } days = -days; negative = true; } if (months < 0) { months = -months; negative = true; } var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); const w = &out.writer; writeSpanTo(w, negative, months, days, nanoseconds) catch return error.OutOfMemory; return .{ .string = try out.toOwnedSlice() }; } fn writeSpanTo( w: *std.Io.Writer, negative: bool, all_months: i64, days: i64, nanoseconds: i128, ) std.Io.Writer.Error!void { if (negative) try w.writeByte('-'); try w.writeByte('P'); const years = @divTrunc(all_months, 12); const months = all_months - years * 12; if (years != 0) try w.print("{d}Y", .{years}); if (months != 0) try w.print("{d}M", .{months}); if (days != 0) try w.print("{d}D", .{days}); const seconds = @divTrunc(nanoseconds, Duration.nanoseconds_per_second); const fraction = nanoseconds - seconds * Duration.nanoseconds_per_second; if (seconds == 0 and fraction == 0) return; try w.writeByte('T'); // Each unit is written only when there is enough left for it, so an hour // exactly is `PT1H` and not `PT1H0M0S`. var rest = seconds; if (rest >= 3600) { try w.print("{d}H", .{@divTrunc(rest, 3600)}); rest -= @divTrunc(rest, 3600) * 3600; } if (rest >= 60) { try w.print("{d}M", .{@divTrunc(rest, 60)}); rest -= @divTrunc(rest, 60) * 60; } if (rest > 0 or fraction > 0) { try w.print("{d}", .{rest}); try writeFraction(w, @intCast(fraction)); try w.writeByte('S'); } } /// A duration argument, or null when the text is not one. /// /// XML Schema allows a decimal fraction only on the seconds, which is /// stricter than ISO 8601 -- so `P1.5D` is refused here even though the /// parser can read it. fn durationArg(gpa: std.mem.Allocator, arg: Value) Error!?Duration { const text = try arg.toString(gpa); defer gpa.free(text); const parsed = datetime.iso8601.parseDuration(text) catch return null; if (parsed.str.len != text.len) return null; if (parsed.fractional) |unit| if (unit != 'S') return null; return normalize(parsed.value); } fn add(gpa: std.mem.Allocator, date_arg: Value, duration_arg: Value) Error!Value { const text = try date_arg.toString(gpa); defer gpa.free(text); const s = parse(text) orelse return empty(gpa); // Only the four right-truncated date types can be added to. if (!s.kind.has(.g_year)) return empty(gpa); const d = try durationArg(gpa, duration_arg) orelse return empty(gpa); // The calendar's year is an `i32`, and a duration big enough to push the // result past it has no answer to give. Checked here, in the width the // arithmetic cannot overflow, rather than left to trap inside it. const total_months = @as(i128, s.dt.year) * 12 + (@as(i128, @backingInt(s.dt.month)) - 1) + d.months; const landing_year = @divFloor(total_months, 12); if (landing_year < std.math.minInt(i32) or landing_year > std.math.maxInt(i32)) { return empty(gpa); } const span = @as(i128, datetime.Date.max_days) - datetime.Date.min_days; if (@abs(d.days) > span) return empty(gpa); const result = s.dt.add(d); // Which type the answer is written in is decided by what the arithmetic // produced rather than by what went in, and libxslt's rule is that a // component is shown once it stops being the default. So a gYearMonth // plus three days is a date, while the same plus thirty-one days lands on // the 1st and stays a gYearMonth. var kind = s.kind; if (kind != .date_time) { if (result.hour != 0 or result.minute != 0 or result.second != 0 or result.nanosecond != 0) { kind = .date_time; } else if (kind != .date) { if (result.day != 1) { kind = .date; } else if (kind != .g_year_month and @backingInt(result.month) != 1) { kind = .g_year_month; } } } return try string(gpa, .{ .kind = kind, .dt = result, .has_offset = s.has_offset }); } fn difference(gpa: std.mem.Allocator, first: Value, second: Value) Error!Value { const x_text = try first.toString(gpa); defer gpa.free(x_text); const y_text = try second.toString(gpa); defer gpa.free(y_text); var x = parse(x_text) orelse return empty(gpa); var y = parse(y_text) orelse return empty(gpa); if (!x.kind.has(.g_year) or !y.kind.has(.g_year)) return empty(gpa); // The more specific operand is truncated to the less specific one, so // that a difference is taken between two things of the same shape. if (@backingInt(x.kind) < @backingInt(y.kind)) { y = truncate(y, x.kind); } else if (@backingInt(y.kind) < @backingInt(x.kind)) { x = truncate(x, y.kind); } // Two values that name no day are a whole number of months apart, and // saying so is more useful than a day count that depends on which months // they were. if (x.kind == .g_year or x.kind == .g_year_month) { const months = (@as(i64, y.dt.year) - x.dt.year) * 12 + (@as(i64, @backingInt(y.dt.month)) - @backingInt(x.dt.month)); return try writeDuration(gpa, .{ .months = months }); } var nanoseconds = timeOfDay(y.dt) - timeOfDay(x.dt); nanoseconds += (@as(i128, x.dt.offset) - y.dt.offset) * Duration.nanoseconds_per_second; const carry = @divFloor(nanoseconds, Duration.nanoseconds_per_day); nanoseconds -= carry * Duration.nanoseconds_per_day; const days = @as(i64, @intCast(carry)) + (asDate(y.dt).toDaysSinceStartOfEra() - asDate(x.dt).toDaysSinceStartOfEra()); return try writeDuration(gpa, normalize(.{ .days = days, .nanoseconds = nanoseconds })); } fn secondsOf(gpa: std.mem.Allocator, args: []const Value, now: ?DateTime) Error!f64 { const dt: DateTime = blk: { if (args.len == 0) break :blk now orelse return std.math.nan(f64); const text = try args[0].toString(gpa); defer gpa.free(text); if (parse(text)) |s| { if (!s.kind.has(.g_year)) return std.math.nan(f64); break :blk s.dt; } // Not a date, so try a duration. One that names months has no length // in seconds, and NaN is the honest answer. const d = try durationArg(gpa, args[0]) orelse return std.math.nan(f64); if (d.months != 0) return std.math.nan(f64); return @as(f64, @floatFromInt(d.days)) * 86400.0 + @as(f64, @floatFromInt(d.nanoseconds)) / 1_000_000_000.0; }; const epoch: datetime.Date = .{ .year = 1970, .month = .Jan, .day = 1 }; const days = asDate(dt).toDaysSinceStartOfEra() - epoch.toDaysSinceStartOfEra(); return @as(f64, @floatFromInt(days)) * 86400.0 + @as(f64, @floatFromInt(timeOfDay(dt))) / 1_000_000_000.0 - @as(f64, @floatFromInt(dt.offset)); } /// Drops the parts a less specific type does not carry, putting each back to /// the value it defaults to. fn truncate(s: Stamp, kind: Kind) Stamp { var out = s; if (!kind.has(.time)) { out.dt.hour = 0; out.dt.minute = 0; out.dt.second = 0; out.dt.nanosecond = 0; } if (!kind.has(.g_day)) out.dt.day = 1; if (!kind.has(.g_month)) out.dt.month = .Jan; if (!kind.has(.g_year)) out.dt.year = 0; out.kind = kind; return out; } fn asDate(dt: DateTime) datetime.Date { return .{ .year = dt.year, .month = dt.month, .day = dt.day }; } fn timeOfDay(dt: DateTime) i128 { return @as(i128, dt.hour) * Duration.nanoseconds_per_hour + @as(i128, dt.minute) * Duration.nanoseconds_per_minute + @as(i128, dt.second) * Duration.nanoseconds_per_second + dt.nanosecond; } fn dayInYear(date: datetime.Date) i32 { const january: datetime.Date = .{ .year = date.year, .month = .Jan, .day = 1 }; return @intCast(date.toDaysSinceStartOfEra() - january.toDaysSinceStartOfEra() + 1); } fn monthName(month: datetime.Month) []const u8 { return switch (month) { .Jan => "January", .Feb => "February", .Mar => "March", .Apr => "April", .May => "May", .Jun => "June", .Jul => "July", .Aug => "August", .Sep => "September", .Oct => "October", .Nov => "November", .Dec => "December", }; } fn dayName(day: datetime.DayOfWeek) []const u8 { return switch (day) { .Sun => "Sunday", .Mon => "Monday", .Tue => "Tuesday", .Wed => "Wednesday", .Thu => "Thursday", .Fri => "Friday", .Sat => "Saturday", }; } // -- tests ------------------------------------------------------------------- const testing = std.testing; fn expectRoundTrip(text: []const u8, kind: Kind) !void { const s = parse(text) orelse { std.debug.print("did not parse: {s}\n", .{text}); return error.TestUnexpectedResult; }; try testing.expectEqual(kind, s.kind); const written = try toOwnedString(testing.allocator, s); defer testing.allocator.free(written); try testing.expectEqualStrings(text, written); } test "every one of XML Schema's date types round-trips" { try expectRoundTrip("2001-02-28T10:31:07Z", .date_time); try expectRoundTrip("2001-02-28T10:31:07.5Z", .date_time); try expectRoundTrip("2001-02-28T10:31:07-05:00", .date_time); try expectRoundTrip("2001-02-28", .date); try expectRoundTrip("2001-02-28Z", .date); try expectRoundTrip("2001-02", .g_year_month); try expectRoundTrip("2001", .g_year); try expectRoundTrip("--02-28", .g_month_day); try expectRoundTrip("--02--", .g_month); try expectRoundTrip("---28", .g_day); try expectRoundTrip("10:31:07", .time); try expectRoundTrip("10:31:07Z", .time); // Years beyond four digits, and the negative ones. try expectRoundTrip("10000", .g_year); try expectRoundTrip("-0001", .g_year); try expectRoundTrip("-10000-12-31T23:59:59Z", .date_time); } test "a dateTime with no timezone is written with one anyway" { // Not a mistake: libxslt's dateTime formatter writes the offset // unconditionally where its other formatters ask whether there was one, // and matching it is the difference between agreeing with every other // processor and disagreeing with all of them. const s = parse("2001-02-28T10:31:07").?; try testing.expect(!s.has_offset); const written = try toOwnedString(testing.allocator, s); defer testing.allocator.free(written); try testing.expectEqualStrings("2001-02-28T10:31:07Z", written); // A date, a time and a gYear are not written that way. for ([_][]const u8{ "2001-02-28", "10:31:07", "2001" }) |text| { const plain = try toOwnedString(testing.allocator, parse(text).?); defer testing.allocator.free(plain); try testing.expectEqualStrings(text, plain); } } test "XML Schema's years have no zero" { // `-0001` is 1 BCE, which the calendar underneath numbers 0 -- so the // year *after* `-0001` is `0001`, and there is no year between them. const minus_one = parse("-0001").?; try testing.expectEqual(@as(i32, 0), minus_one.dt.year); try testing.expectEqual(@as(i64, -1), minus_one.schemaYear()); const one = parse("0001").?; try testing.expectEqual(@as(i32, 1), one.dt.year); try testing.expectEqual(@as(i64, 1), one.schemaYear()); // And `0000` is not a year at all. try testing.expect(parse("0000") == null); } test "nothing but a whole date type parses" { // `--02-30` is not among these: a gMonthDay names no year, so nothing can // decide whether February has a 30th, and libxslt accepts any day from 1 // to 31 for that reason. try testing.expect(parse("--02-30") != null); for ([_][]const u8{ "", "bogus", "2001-", "2001-13", "2001-02-30", "2001-02-28T10:31", "10:31", "--13-01", "---32", "--02", "2001-02-28T10:31:07+", "2001-02-28 ", // Three digits is not a year, and neither is a five-digit one with a // leading zero. "001", "01000", // Trailing text is not allowed here, unlike in the ISO 8601 parser: // a date function is handed a whole string and either it is a date or // it is not. "2001-02-28 and more", }) |bad| { testing.expect(parse(bad) == null) catch |err| { std.debug.print("parsed but should not have: \"{s}\"\n", .{bad}); return err; }; } } fn expectCall(expected: []const u8, local: []const u8, args: []const Value) !void { const gpa = testing.allocator; const got = (try call(gpa, local, args, null)).?; defer got.deinit(gpa); const text = try got.toString(gpa); defer gpa.free(text); try testing.expectEqualStrings(expected, text); } fn str(s: []const u8) Value { return .{ .string = @constCast(s) }; } test "date:add writes the answer in the type the arithmetic produced" { // The type is decided by what came out rather than by what went in, and // libxslt's rule is that a component appears once it stops being the // default. A gYearMonth plus three days is a date; the same plus // thirty-one days lands on the first and stays a gYearMonth. try expectCall("2001-01-04", "add", &.{ str("2001-01"), str("P3D") }); try expectCall("2001-12-31", "add", &.{ str("2001-12"), str("P30D") }); try expectCall("2002-01", "add", &.{ str("2001-12"), str("P31D") }); try expectCall("2002-01-02", "add", &.{ str("2001-12"), str("P32D") }); // The clamp, before the days are added. try expectCall("2001-02-28", "add", &.{ str("2001-01-31"), str("P1M") }); // Across the year the calendar has no zero for. try expectCall("0001-01-01T00:00:00Z", "add", &.{ str("-0001-12-31T23:59:59"), str("PT1S") }); // A fraction on anything but the seconds is not an `xs:duration`. try expectCall("", "add", &.{ str("2001-12-01"), str("P1.5D") }); try expectCall("2001-12-01T00:00:01.5Z", "add", &.{ str("2001-12-01"), str("PT1.5S") }); } test "a duration that would have to borrow has no answer" { // EXSLT's rule, and it is about borrowing rather than about signs: months // and days are not commensurable, so a positive number of months and a // negative number of days is a length of time nobody can write. The same // three durations summed in a different order succeed. try expectCall("", "add-duration", &.{ str("P1M"), str("-P1D") }); try expectCall("P0D", "add-duration", &.{ str("P1D"), str("-PT24H") }); try expectCall("P31D", "add-duration", &.{ str("P30D"), str("PT24H") }); try expectCall("P13Y9M", "add-duration", &.{ str("P10Y"), str("P45M") }); } test "date:duration folds seconds into days" { try expectCall("PT1M", "duration", &.{.{ .number = 60 }}); try expectCall("P1D", "duration", &.{.{ .number = 86400 }}); try expectCall("P1DT0.5S", "duration", &.{.{ .number = 86400.5 }}); try expectCall("-PT1M", "duration", &.{.{ .number = -60 }}); try expectCall("P0D", "duration", &.{.{ .number = 0 }}); // Rounding the remainder can reach a whole unit. try expectCall("PT1H", "duration", &.{.{ .number = 3599.99999999999 }}); // A day count past what an integer can hold is no duration. try expectCall("", "duration", &.{.{ .number = 1e25 }}); } test "an accessor answers only for the types that carry what it asks about" { try expectCall("2001", "year", &.{str("2001-02-28")}); try expectCall("NaN", "year", &.{str("--02-28")}); try expectCall("February", "month-name", &.{str("--02-28")}); try expectCall("", "month-name", &.{str("---28")}); try expectCall("NaN", "hour-in-day", &.{str("2001-02-28")}); try expectCall("10", "hour-in-day", &.{str("10:31:07")}); // A year is a leap year by the astronomical numbering, so 1 BCE -- which // is year 0 -- is one. try expectCall("true", "leap-year", &.{str("-0001")}); try expectCall("false", "leap-year", &.{str("2001")}); // With no clock to read, the no-argument forms answer as they do for a // date they cannot read. try expectCall("", "date-time", &.{}); try expectCall("NaN", "year", &.{}); }