From 5a342ad1a58a61812bfcad36f1664ecfbf9529bb Mon Sep 17 00:00:00 2001 From: Malte Ubl Date: Sun, 18 Oct 2026 12:17:25 -0700 Subject: [PATCH] Parse date strings with V8's grammar when the bounded parser rejects them Date.parse and new Date(string) answered NaN natively for every form outside ISO 8601 with an explicit offset and the X509 certificate shape, so RFC 1123 HTTP dates ("Mon, 01 Jan 2024 00:00:00 GMT") never parsed and the fresh/express/send conditional GET never matched. The runtime now falls back to a port of V8's DateParser (the ES5 date-time format, then the Safari-compatible legacy grammar: weekday and month names, RFC 2822 offsets, zone abbreviations, AM/PM, parenthesized comments, slashes) for exactly the strings the bounded grammars reject, so the timestamps they accept cost nothing more. Zone-less dates are local time, converted with the spec's UTC(t) over the host zone (DST gaps read with the offset before the transition, overlaps answer the earlier instant). With native parsing matching Node for every input, the SC6005 literal warning has nothing left to report and is retired rather than extended to non-literal inputs. Co-Authored-By: Claude Opus 5.5 --- docs/content/docs/coverage.mdx | 1 - .../limitations/dates-and-timezones.mdx | 4 +- .../compiler/src/diagnostics/diagnostic.ts | 17 +- .../src/frontend/lowering/builtins/dates.ts | 5 +- .../src/frontend/lowering/divergences.ts | 75 --- .../src/frontend/lowering/surfaces.ts | 2 +- .../compiler/src/ir/builtin-signatures.ts | 11 +- packages/compiler/surface-manifest.json | 2 +- .../corpus/6230-date-parse-legacy.ts.json | 6 + packages/runtime/src/scr_lib.c | 633 +++++++++++++++++- packages/runtime/src/scr_number.h | 5 +- tests/corpus/6230-date-parse-legacy.ts | 112 ++++ tests/coverage-fixtures/divergences.ts | 2 +- .../__snapshots__/coverage-divergences.txt | 13 +- tests/harness/coverage.test.ts | 7 +- 15 files changed, 766 insertions(+), 129 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6230-date-parse-legacy.ts.json create mode 100644 tests/corpus/6230-date-parse-legacy.ts diff --git a/docs/content/docs/coverage.mdx b/docs/content/docs/coverage.mdx index 2d26e684b..9c9ec413f 100644 --- a/docs/content/docs/coverage.mdx +++ b/docs/content/docs/coverage.mdx @@ -68,7 +68,6 @@ Some code compiles but can behave differently than under Node.js. Coverage repor - `SC6002`: an object literal's key order differs from its type's declaration order, and the program observes the order through `JSON.stringify`, `Object.keys`, `Object.values`, `Object.entries`, `for...in`, or console output. - `SC6003`: `localeCompare` compares a string literal outside the built-in Latin-script collation. - `SC6004`: a call passes a class instance to a function that casts it to an unrelated class. -- `SC6005`: a `Date` string literal uses a form the native parser does not accept. ## Gating builds and CI diff --git a/docs/content/limitations/dates-and-timezones.mdx b/docs/content/limitations/dates-and-timezones.mdx index ad830eb9a..eacaf29d0 100644 --- a/docs/content/limitations/dates-and-timezones.mdx +++ b/docs/content/limitations/dates-and-timezones.mdx @@ -1,3 +1,3 @@ -String constructors and `Date.parse` accept ECMAScript date-only forms, date-times with an explicit `Z` or numeric offset, and GMT certificate-validity strings from the supported X509 APIs. Other V8-specific forms and offset-less local date-times produce an Invalid Date or `NaN`; `SC6005` reports string literals in those forms. +String constructors and `Date.parse` use V8's date-string grammar: ECMAScript date-time strings and the legacy forms Node.js accepts, such as RFC 1123 HTTP dates (`Mon, 01 Jan 2024 00:00:00 GMT`), `Date#toString` output, and `Jan 2, 2024`. Strings without a timezone are local time. -Local calendar getters use the operating system's timezone database. Historical results can differ from Node.js when timezone data differs. For valid extreme years outside a platform calendar API's range, scriptc uses a calendar-equivalent year in the 400-year Gregorian cycle to obtain the timezone rule. +Local calendar getters and local-time conversions use the operating system's timezone database. Historical results can differ from Node.js when timezone data differs. For valid extreme years outside a platform calendar API's range, scriptc uses a calendar-equivalent year in the 400-year Gregorian cycle to obtain the timezone rule. diff --git a/packages/compiler/src/diagnostics/diagnostic.ts b/packages/compiler/src/diagnostics/diagnostic.ts index eaae1b531..da4da347a 100644 --- a/packages/compiler/src/diagnostics/diagnostic.ts +++ b/packages/compiler/src/diagnostics/diagnostic.ts @@ -59,8 +59,9 @@ * order that differs from insertion order where the program * observes it (SC6002), localeCompare over text the built-in * collation does not cover (SC6003), a call feeding an instance - * to a cast to an unrelated class (SC6004), and Date strings the native parser does not - * accept (SC6005) + * to a cast to an unrelated class (SC6004); SC6005 (Date strings + * outside the native parser's grammar) is retired — the runtime + * parses date strings with V8's grammar * SC9xxx internal compiler errors (still source-anchored) */ import type { SrcLoc } from "../ir/ir.js"; @@ -200,18 +201,6 @@ export function unrelatedClassCastDivergenceDiag( }; } -/** SC6005 — a Date string literal outside the grammar the native parser - * accepts (ISO 8601 with an explicit offset, date-only forms, and the - * certificate-time shape): Node parses many more forms. */ -export function dateLiteralDivergenceDiag(text: string, loc: SrcLoc): ScrDiagnostic { - return { - code: "SC6005", - message: `the date string '${text}' parses to an invalid date (NaN) natively, while Node accepts it (the native parser takes ISO 8601 date-times with an explicit offset, such as '2024-01-02T03:04:05Z', and date-only forms)`, - loc, - hint: "write the date in ISO 8601 with an explicit offset ('Z' or '+HH:MM'), or build it from numbers with Date.UTC", - }; -} - /* ── SC5xxx: native FFI ───────────────────────────────────────────────── */ /** SC5001 — the outbound native-FFI manifest is malformed or unreadable. */ diff --git a/packages/compiler/src/frontend/lowering/builtins/dates.ts b/packages/compiler/src/frontend/lowering/builtins/dates.ts index fa880bdc9..7c5a276ac 100644 --- a/packages/compiler/src/frontend/lowering/builtins/dates.ts +++ b/packages/compiler/src/frontend/lowering/builtins/dates.ts @@ -52,9 +52,8 @@ export function lowerDateCall( } return { kind: "libCall", fn: "date.now", args: [], type: F64, loc }; } - // Date.parse uses the same bounded date-string parser as - // new Date(dateString).getTime(); keep their NaN and TimeClip behavior - // identical for the ISO timestamps used by CLI applications. + // Date.parse uses the same date-string parser as new Date(dateString) + // (V8's grammar in the runtime), so their NaN and TimeClip behavior agree. if (lowerer.stdlibGlobalMember(access, "Date") === "parse") { if (call.arguments.length !== 1 || ts.isSpreadElement(call.arguments[0]!)) { lowerer.noLowering(`Date.parse with ${call.arguments.length} arguments`, call); diff --git a/packages/compiler/src/frontend/lowering/divergences.ts b/packages/compiler/src/frontend/lowering/divergences.ts index 2a9009aed..004cb55a1 100644 --- a/packages/compiler/src/frontend/lowering/divergences.ts +++ b/packages/compiler/src/frontend/lowering/divergences.ts @@ -14,7 +14,6 @@ import * as ts from "../ts7/adapter.js"; import { locOf } from "../program.js"; import { isNodeModulesPath } from "../resolve.js"; import { - dateLiteralDivergenceDiag, keyOrderDivergenceDiag, localeCompareDivergenceDiag, unrelatedClassCastDivergenceDiag, @@ -56,7 +55,6 @@ export function scanDivergences( const literals: ts.ObjectLiteralExpression[] = []; const observers: ts.Expression[] = []; const casts: (ts.AsExpression | ts.TypeAssertion)[] = []; - const dates: { call: ts.CallExpression | ts.NewExpression; arg: ts.Expression }[] = []; const localeCompares: ts.CallExpression[] = []; /** binding name → member names assigned through it (`q.a = 2`). */ const assignedMembers = new Map>(); @@ -97,19 +95,9 @@ export function scanDivergences( member === "dir") ) { for (const a of node.arguments) if (!isLiteralLike(a)) observers.push(a); - } else if (recv.text === "Date" && member === "parse") { - if (node.arguments[0] !== undefined) dates.push({ call: node, arg: node.arguments[0] }); } } } - } else if (ts.isNewExpression(node)) { - if ( - ts.isIdentifier(node.expression) && - node.expression.text === "Date" && - node.arguments?.length === 1 - ) { - dates.push({ call: node, arg: node.arguments[0]! }); - } } else if (ts.isForInStatement(node)) { observers.push(node.expression); } else if (ts.isVariableDeclaration(node)) { @@ -397,55 +385,9 @@ export function scanDivergences( } } - // ── Date strings the native parser does not accept ──────────────── - for (const { call, arg } of dates) { - const callee = ts.isNewExpression(call) - ? call.expression - : ts.isPropertyAccessExpression(call.expression) - ? call.expression.expression - : undefined; - if (callee === undefined || !lowerer.isStdlibGlobal(callee, "Date")) continue; - for (const literal of dateStringLiterals(checker, arg)) { - const text = stringLiteralText(literal)!; - if (nativeDateParses(text) || !/\d/.test(text)) continue; - out.push(dateLiteralDivergenceDiag(text, locOf(literal))); - } - } - return out; } -/** The string literals a Date argument can be: the literal itself, or - * each element of a const array of literals a for-of binding iterates. */ -function dateStringLiterals(checker: ts.TypeChecker, arg: ts.Expression): ts.Expression[] { - if (stringLiteralText(arg) !== null) return [arg]; - if (!ts.isIdentifier(arg)) return []; - const symbol = safely(() => checker.getSymbolAtLocation(arg)); - const decl = symbol === undefined ? undefined : checker.valueDeclarationOf(symbol); - const list = decl?.parent; - const loop = list?.parent; - if ( - decl === undefined || - !ts.isVariableDeclaration(decl) || - list === undefined || - loop === undefined || - !ts.isForOfStatement(loop) || - loop.initializer !== list - ) - return []; - let iterated: ts.Expression = loop.expression; - if (ts.isIdentifier(iterated)) { - const source = safely(() => checker.getSymbolAtLocation(iterated)); - const init = source === undefined ? undefined : checker.valueDeclarationOf(source); - if (init === undefined || !ts.isVariableDeclaration(init) || init.initializer === undefined) - return []; - if (init.parent === undefined || (init.parent.flags & ts.NodeFlags.Const) === 0) return []; - iterated = init.initializer; - } - if (!ts.isArrayLiteralExpression(iterated)) return []; - return iterated.elements.filter((e) => stringLiteralText(e) !== null); -} - /** A checker query that fails here only loses a warning. */ function safely(f: () => T): T | undefined { try { @@ -857,20 +799,3 @@ function classExtends( function className(decl: ts.ClassLikeDeclaration): string { return decl.name?.text ?? "(anonymous class)"; } - -const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]; - -/** The date-string grammar the native runtime accepts (scr_lib.c - * scr_date_parse_get_time): ECMAScript's date-time format with an explicit - * offset (date-only forms are UTC) and the certificate-time shape - * "Mon DD HH:MM:SS YYYY GMT". Everything else parses to NaN natively. */ -export function nativeDateParses(text: string): boolean { - const iso = - /^(?:[+-]\d{6}|\d{4})(?:-(\d{2})(?:-(\d{2}))?)?$/.test(text) || - /^(?:[+-]\d{6}|\d{4})-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{3})?)?(?:Z|[+-]\d{2}:\d{2})$/.test( - text, - ); - if (iso) return true; - const cert = /^([A-Za-z]{3}) {1,2}\d{1,2} \d{2}:\d{2}:\d{2} \d{4} GMT$/.exec(text); - return cert !== null && MONTHS.includes(cert[1]!.toLowerCase()); -} diff --git a/packages/compiler/src/frontend/lowering/surfaces.ts b/packages/compiler/src/frontend/lowering/surfaces.ts index d394c1960..561a58953 100644 --- a/packages/compiler/src/frontend/lowering/surfaces.ts +++ b/packages/compiler/src/frontend/lowering/surfaces.ts @@ -2170,7 +2170,7 @@ export const AMBIENT_SURFACE_FNS: readonly AmbientSurfaceRow[] = [ kind: "stdlib", name: "Date.parse", fns: ["date.parse"], - note: "one date string, using the bounded parser shared with new Date(dateString).getTime()", + note: "one date string, using V8's date parser shared with new Date(dateString)", }, { id: "stdlib.date.constructor", diff --git a/packages/compiler/src/ir/builtin-signatures.ts b/packages/compiler/src/ir/builtin-signatures.ts index 08c493ae4..1d14d8732 100644 --- a/packages/compiler/src/ir/builtin-signatures.ts +++ b/packages/compiler/src/ir/builtin-signatures.ts @@ -4187,13 +4187,10 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ "date.getUTCMilliseconds": { argTypes: [DATE_T], result: F64 }, "date.getTimezoneOffset": { argTypes: [DATE_T], result: F64 }, /** The composed `new Date(dateString).getTime()` read: one borrowed - * string, f64 milliseconds since epoch. The parsed grammar is BOUNDED - * (documented divergence — V8's parser accepts far more): the ASN.1 - * validity shape X509Certificate.validFrom/validTo answer ("Jul 1 - * 00:00:00 2026 GMT" — the portless cert-expiry read), and ECMA's own - * date-time string format (YYYY-MM-DD[THH:mm[:ss[.sss]]][Z|±HH:MM] — - * date-only forms are UTC, exactly the spec). Anything else is NaN, - * Node's invalid-date getTime. Never throws. */ + * string, f64 milliseconds since epoch, with V8's date-string grammar + * (the ES5 format, then the legacy forms: RFC 1123/2822, Date#toString, + * "Jan 2, 2024", ...). Zone-less dates are local time; anything V8 + * rejects is NaN, Node's invalid-date getTime. Never throws. */ "date.parseGetTime": { argTypes: [STRING], result: F64 }, /** `Date.UTC(...)` — seven f64 arguments (the frontend completes the * spec's defaults for omitted trailing parts: month 0, date 1, time diff --git a/packages/compiler/surface-manifest.json b/packages/compiler/surface-manifest.json index f5313f12d..471210669 100644 --- a/packages/compiler/surface-manifest.json +++ b/packages/compiler/surface-manifest.json @@ -4150,7 +4150,7 @@ "kind": "stdlib", "name": "Date.parse", "status": "static", - "note": "one date string, using the bounded parser shared with new Date(dateString).getTime()" + "note": "one date string, using V8's date parser shared with new Date(dateString)" }, { "id": "stdlib.date.toISOString", diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6230-date-parse-legacy.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6230-date-parse-legacy.ts.json new file mode 100644 index 000000000..b7cad9619 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6230-date-parse-legacy.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6230-date-parse-legacy.ts" + ], + "diags": [] +} diff --git a/packages/runtime/src/scr_lib.c b/packages/runtime/src/scr_lib.c index fd51e9c78..2c232cbea 100644 --- a/packages/runtime/src/scr_lib.c +++ b/packages/runtime/src/scr_lib.c @@ -10298,9 +10298,9 @@ ScrStr *scr_date_to_iso(double ms) { /* ── new Date(dateString).getTime() ────────────────────────────────────── * - * The BOUNDED date-string parse (documented divergence — V8's parser - * accepts far more): two grammars answer a time value, everything else is - * NaN (Node's invalid-date getTime). + * The BOUNDED date-string parse, the fast path: two grammars answer a time + * value directly; a string they reject falls back to V8's full parser + * (scr_date_parse_v8 below), which also answers everything they accept. * * 1. The ASN1_TIME_print shape X509Certificate.validFrom/validTo answer * ("Jul 1 00:00:00 2026 GMT", "Jul 17 17:52:11 2026 GMT") — the @@ -10309,8 +10309,8 @@ ScrStr *scr_date_to_iso(double ms) { * 2. ECMA's own date-time string format with an EXPLICIT offset: * YYYY[-MM[-DD]] date-only forms (UTC, per the spec) and full * date-times YYYY-MM-DDTHH:mm[:ss[.sss]] ending in Z or ±HH:MM. - * Offset-less date-times are LOCAL time in JS; that arm answers NaN - * here rather than guessing a zone (the divergence note). + * Offset-less date-times are LOCAL time in JS; they take the + * fallback, which converts them in the host zone. */ /* Howard Hinnant's days_from_civil (the to_iso walk inverted). */ @@ -10351,7 +10351,9 @@ static bool scr_date_digits(const char **p, const char *end, int n, int *out) { return true; } -double scr_date_parse_get_time(ScrStr *s) { +static double scr_date_parse_v8(ScrStr *s); + +static double scr_date_parse_bounded(ScrStr *s) { const char *p = s->data; const char *end = s->data + s->len; static const char *mon[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", @@ -10444,6 +10446,13 @@ double scr_date_parse_get_time(ScrStr *s) { } } +/* The bounded grammars answer first; only a string they reject reaches + * V8's full parser, so the timestamps they accept cost nothing more. */ +double scr_date_parse_get_time(ScrStr *s) { + double t = scr_date_parse_bounded(s); + return isnan(t) ? scr_date_parse_v8(s) : t; +} + /* Date.UTC(year, month, date, hours, minutes, seconds, ms) — the spec's * MakeDay/MakeTime/TimeClip pipeline over ALREADY-NUMBER arguments (tsc * pins them; the frontend completes omitted trailing arguments with the @@ -10647,6 +10656,618 @@ double scr_date_get_timezone_offset(double ms) { return scr_date_local_parts(ms, &p) ? p.timezone_offset : NAN; } +/* ── Local time to UTC ───────────────────────────────────────────────── + * The spec's UTC(t) over the host zone: t is a local wall-clock time + * value. The offset in effect a day before and a day after t brackets any + * transition (none come closer together than that in tzdata). A time in + * a DST overlap has two instants and answers the earlier; a time in a gap + * has none and is read with the offset BEFORE the transition, exactly + * V8's ICU getOffsetFromLocal(FORMER, FORMER). Offsets come from the same + * localtime/surrogate-year walk as the local getters, so a Date built + * from local fields reads those fields back. */ + +/* The host zone's offset (local - UTC) in ms at UTC instant `ms` (an + * integral time value within about ±8.65e15). */ +static bool scr_date_offset_at(double ms, double *out) { + long long cms = (long long)ms; + double secd = (double)(cms / 1000 - (cms % 1000 < 0)); + struct tm tmv; + double basis_secd = secd; + if (!scr_date_localtime(basis_secd, &tmv)) { + ScrDateParts utc; + scr_date_utc_parts_unchecked(ms, &utc); + long long cycle_year = (utc.year - 2000) % 400; + if (cycle_year < 0) cycle_year += 400; + basis_secd = + scr_days_from_civil(2000 + cycle_year, utc.month + 1, utc.date) * 86400.0 + + utc.hours * 3600.0 + utc.minutes * 60.0 + utc.seconds; + if (!scr_date_localtime(basis_secd, &tmv)) return false; + } + double local_as_utc = + scr_days_from_civil((long long)tmv.tm_year + 1900, tmv.tm_mon + 1, tmv.tm_mday) * 86400.0 + + tmv.tm_hour * 3600.0 + tmv.tm_min * 60.0 + tmv.tm_sec; + *out = (local_as_utc - basis_secd) * 1000.0; + return true; +} + +static double scr_date_local_to_utc(double t) { + double before, after, at_first, at_second; + if (!scr_date_offset_at(t - 86400000.0, &before) || + !scr_date_offset_at(t + 86400000.0, &after)) { + return NAN; + } + double first = t - before; + if (!scr_date_offset_at(first, &at_first)) return NAN; + if (before == after) { + if (at_first == before) return first; + /* Two transitions inside the window: settle on the instant's own offset. */ + double again = t - at_first, at_again; + if (scr_date_offset_at(again, &at_again) && at_again == at_first) return again; + return first; + } + double second = t - after; + if (!scr_date_offset_at(second, &at_second)) return NAN; + bool first_ok = at_first == before, second_ok = at_second == after; + if (first_ok && second_ok) return first < second ? first : second; /* overlap */ + if (second_ok && !first_ok) return second; + return first; /* the earlier offset's instant, or a gap */ +} + +/* V8's MakeDay (date.cc): bounds the UNtruncated year and month, then + * truncates (FastD2I) and normalizes the month into the year. */ +static double scr_date_v8_make_day(double year, double month, double date) { + if (!(year >= -1000000.0 && year <= 1000000.0 && month >= -10000000.0 && + month <= 10000000.0 && isfinite(date))) { + return NAN; + } + int y = (int)year, m = (int)month; + y += m / 12; + m %= 12; + if (m < 0) { + m += 12; + y -= 1; + } + static const int year_delta = 399999; + static const int base_day = 365 * (1970 + year_delta) + (1970 + year_delta) / 4 - + (1970 + year_delta) / 100 + (1970 + year_delta) / 400; + int day_from_year = 365 * (y + year_delta) + (y + year_delta) / 4 - + (y + year_delta) / 100 + (y + year_delta) / 400 - base_day; + static const int common[12] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}; + static const int leap[12] = {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335}; + bool is_leap = !((y % 4 != 0) || (y % 100 == 0 && y % 400 != 0)); + day_from_year += is_leap ? leap[m] : common[m]; + return (double)(day_from_year - 1) + trunc(date); +} + +static double scr_date_v8_make_time(double h, double m, double s, double ms) { + if (!isfinite(h) || !isfinite(m) || !isfinite(s) || !isfinite(ms)) return NAN; + return trunc(h) * 3600000.0 + trunc(m) * 60000.0 + trunc(s) * 1000.0 + trunc(ms); +} + +/* MakeDate over local fields, then UTC(t) and TimeClip. V8 refuses a local + * time value more than ten days past TimeClip's range before converting. */ +static double scr_date_from_local(double day, double time) { + if (!isfinite(day) || !isfinite(time)) return NAN; + double t = time + day * 86400000.0; + if (!(t >= -8640000864000000.0 && t <= 8640000864000000.0)) return NAN; + return scr_date_new_ms(scr_date_local_to_utc(trunc(t))); +} + +/* ── V8's date-string parser, the fallback ───────────────────────────── + * scr_date_parse_get_time answers its bounded grammars directly and asks + * this parser only when they produce NaN. It follows V8's DateParser + * (dateparser.cc, dateparser-inl.h) step for step: the ES5 date-time + * format first, then the Safari-compatible legacy grammar for whatever + * is left (RFC 1123/2822 HTTP dates, Date#toString output, "Jan 2, 2024", + * "2024/01/02 10:00", ...). Strings are read as UTF-16 code units, and a + * NUL unit ends the input, as in V8. A date without a zone is local time. */ + +enum { + SCR_DT_INVALID = -6, SCR_DT_UNKNOWN = -5, SCR_DT_SPACE = -4, + SCR_DT_NUMBER = -3, SCR_DT_SYMBOL = -2, SCR_DT_END = -1, + /* keyword tags are their keyword type (>= 0) */ + SCR_DK_WORD = 0, SCR_DK_MONTH = 1, SCR_DK_ZONE = 2, SCR_DK_T = 3, SCR_DK_AMPM = 4, +}; +#define SCR_DT_NONE INT_MAX + +typedef struct { + int tag, length, value; +} ScrDateTok; + +typedef struct { + const unsigned char *p, *end; + uint32_t ch, low; + ScrDateTok next; +} ScrDateScan; + +static void scr_date_scan_advance(ScrDateScan *in) { + if (in->low) { + in->ch = in->low; + in->low = 0; + return; + } + if (in->p >= in->end) { + in->ch = 0; + return; + } + const unsigned char *p = in->p; + size_t left = (size_t)(in->end - p); + uint32_t cp = p[0]; + size_t n = 1; + if (cp >= 0xF0 && left >= 4) { + cp = ((cp & 0x07u) << 18) | ((p[1] & 0x3Fu) << 12) | ((p[2] & 0x3Fu) << 6) | (p[3] & 0x3Fu); + n = 4; + } else if (cp >= 0xE0 && left >= 3) { + cp = ((cp & 0x0Fu) << 12) | ((p[1] & 0x3Fu) << 6) | (p[2] & 0x3Fu); + n = 3; + } else if (cp >= 0xC0 && left >= 2) { + cp = ((cp & 0x1Fu) << 6) | (p[1] & 0x3Fu); + n = 2; + } else if (cp >= 0x80) { + cp = 0xFFFD; + } + in->p += n; + if (cp > 0xFFFF) { + cp -= 0x10000; + in->ch = 0xD800 + (cp >> 10); + in->low = 0xDC00 + (cp & 0x3FF); + } else { + in->ch = cp; + } +} + +/* ECMAScript WhiteSpace, and WhiteSpace or LineTerminator. */ +static bool scr_date_is_space(uint32_t c) { + return c == 0x09 || c == 0x0B || c == 0x0C || c == 0x20 || c == 0xA0 || c == 0xFEFF || + c == 0x1680 || (c >= 0x2000 && c <= 0x200A) || c == 0x202F || c == 0x205F || + c == 0x3000; +} + +static bool scr_date_is_space_or_newline(uint32_t c) { + return scr_date_is_space(c) || c == 0x0A || c == 0x0D || c == 0x2028 || c == 0x2029; +} + +static const struct { + char prefix[3]; + signed char type, value; +} scr_date_keywords[] = { + {{'j', 'a', 'n'}, SCR_DK_MONTH, 1}, {{'f', 'e', 'b'}, SCR_DK_MONTH, 2}, + {{'m', 'a', 'r'}, SCR_DK_MONTH, 3}, {{'a', 'p', 'r'}, SCR_DK_MONTH, 4}, + {{'m', 'a', 'y'}, SCR_DK_MONTH, 5}, {{'j', 'u', 'n'}, SCR_DK_MONTH, 6}, + {{'j', 'u', 'l'}, SCR_DK_MONTH, 7}, {{'a', 'u', 'g'}, SCR_DK_MONTH, 8}, + {{'s', 'e', 'p'}, SCR_DK_MONTH, 9}, {{'o', 'c', 't'}, SCR_DK_MONTH, 10}, + {{'n', 'o', 'v'}, SCR_DK_MONTH, 11}, {{'d', 'e', 'c'}, SCR_DK_MONTH, 12}, + {{'a', 'm', 0}, SCR_DK_AMPM, 0}, {{'p', 'm', 0}, SCR_DK_AMPM, 12}, + {{'u', 't', 0}, SCR_DK_ZONE, 0}, {{'u', 't', 'c'}, SCR_DK_ZONE, 0}, + {{'z', 0, 0}, SCR_DK_ZONE, 0}, {{'g', 'm', 't'}, SCR_DK_ZONE, 0}, + {{'c', 'd', 't'}, SCR_DK_ZONE, -5}, {{'c', 's', 't'}, SCR_DK_ZONE, -6}, + {{'e', 'd', 't'}, SCR_DK_ZONE, -4}, {{'e', 's', 't'}, SCR_DK_ZONE, -5}, + {{'m', 'd', 't'}, SCR_DK_ZONE, -6}, {{'m', 's', 't'}, SCR_DK_ZONE, -7}, + {{'p', 'd', 't'}, SCR_DK_ZONE, -7}, {{'p', 's', 't'}, SCR_DK_ZONE, -8}, + {{'t', 0, 0}, SCR_DK_T, 0}, +}; + +static ScrDateTok scr_date_scan_token(ScrDateScan *in) { + ScrDateTok t = {SCR_DT_UNKNOWN, 1, -1}; + uint32_t c = in->ch; + if (c == 0) { + t.tag = SCR_DT_END; + return t; + } + if (c >= '0' && c <= '9') { + /* Leading zeros count toward the length; past nine significant + * digits the value stops growing but the digits are consumed. */ + int n = 0, digits = 0, length = 0; + while (in->ch == '0') { + scr_date_scan_advance(in); + length++; + } + while (in->ch >= '0' && in->ch <= '9') { + if (digits < 9) n = n * 10 + (int)(in->ch - '0'); + digits++; + length++; + scr_date_scan_advance(in); + } + t.tag = SCR_DT_NUMBER; + t.value = n; + t.length = length; + return t; + } + if (c == ':' || c == '-' || c == '+' || c == '.' || c == ')') { + scr_date_scan_advance(in); + t.tag = SCR_DT_SYMBOL; + t.value = (int)c; + return t; + } + if (c >= 'A' && !scr_date_is_space(c)) { + uint32_t prefix[3] = {0, 0, 0}; + int length = 0; + while (in->ch >= 'A' && !scr_date_is_space(in->ch)) { + if (length < 3) prefix[length] = in->ch | 0x20; + length++; + scr_date_scan_advance(in); + } + t.tag = SCR_DK_WORD; + t.value = 0; + t.length = length; + for (size_t i = 0; i < sizeof scr_date_keywords / sizeof scr_date_keywords[0]; i++) { + const char *k = scr_date_keywords[i].prefix; + if (prefix[0] == (uint32_t)(unsigned char)k[0] && prefix[1] == (uint32_t)(unsigned char)k[1] && + prefix[2] == (uint32_t)(unsigned char)k[2] && + (length <= 3 || scr_date_keywords[i].type == SCR_DK_MONTH)) { + t.tag = scr_date_keywords[i].type; + t.value = scr_date_keywords[i].value; + break; + } + } + return t; + } + if (scr_date_is_space_or_newline(c)) { + scr_date_scan_advance(in); + t.tag = SCR_DT_SPACE; + return t; + } + if (c == '(') { + int balance = 0; + do { + if (in->ch == ')') balance--; + else if (in->ch == '(') balance++; + scr_date_scan_advance(in); + } while (balance > 0 && in->ch); + return t; + } + scr_date_scan_advance(in); + return t; +} + +static ScrDateTok scr_date_next(ScrDateScan *in) { + ScrDateTok t = in->next; + in->next = scr_date_scan_token(in); + return t; +} + +static bool scr_date_tok_symbol(ScrDateTok t, int c) { + return t.tag == SCR_DT_SYMBOL && t.value == c; +} + +static bool scr_date_skip(ScrDateScan *in, int c) { + if (!scr_date_tok_symbol(in->next, c)) return false; + in->next = scr_date_scan_token(in); + return true; +} + +static bool scr_date_tok_sign(ScrDateTok t) { + return t.tag == SCR_DT_SYMBOL && (t.value == '-' || t.value == '+'); +} + +static bool scr_date_tok_fixed(ScrDateTok t, int length) { + return t.tag == SCR_DT_NUMBER && t.length == length; +} + +static bool scr_date_tok_z(ScrDateTok t) { + return t.tag == SCR_DK_ZONE && t.length == 1 && t.value == 0; +} + +static bool scr_date_between(int x, int lo, int hi) { return x >= lo && x <= hi; } + +typedef struct { + int comp[3], index, named_month; + bool iso; +} ScrDateDay; + +typedef struct { + int comp[4], index, hour_offset; +} ScrDateTime; + +typedef struct { + int sign, hour, minute; +} ScrDateZone; + +static bool scr_date_day_add(ScrDateDay *d, int n) { + if (d->index >= 3) return false; + d->comp[d->index++] = n; + return true; +} + +static bool scr_date_time_add(ScrDateTime *t, int n) { + if (t->index >= 4) return false; + t->comp[t->index++] = n; + return true; +} + +static bool scr_date_time_add_final(ScrDateTime *t, int n) { + if (!scr_date_time_add(t, n)) return false; + while (t->index < 4) t->comp[t->index++] = 0; + return true; +} + +static bool scr_date_time_expecting(const ScrDateTime *t, int n) { + return (t->index == 1 && scr_date_between(n, 0, 59)) || + (t->index == 2 && scr_date_between(n, 0, 59)) || + (t->index == 3 && scr_date_between(n, 0, 999)); +} + +static void scr_date_zone_set(ScrDateZone *z, int hours) { + z->sign = hours < 0 ? -1 : 1; + z->hour = hours * z->sign; + z->minute = 0; +} + +static bool scr_date_zone_expecting(const ScrDateZone *z, int n) { + return z->hour != SCR_DT_NONE && z->minute == SCR_DT_NONE && scr_date_between(n, 0, 59); +} + +/* ReadMilliseconds: the first three significant digits of the numeral. */ +static int scr_date_millis(ScrDateTok t) { + int number = t.value, length = t.length; + if (length == 1) number *= 100; + else if (length == 2) number *= 10; + else if (length > 3) { + if (length > 9) length = 9; + int factor = 1; + do { + factor *= 10; + length--; + } while (length > 3); + number /= factor; + } + return number; +} + +/* ParseES5DateTime: answers the first token it could not place (the + * legacy grammar resumes there), END after a complete ES5 string, or + * INVALID for a malformed ES5 time part. */ +static ScrDateTok scr_date_parse_es5(ScrDateScan *in, ScrDateDay *day, ScrDateTime *time, + ScrDateZone *tz) { + ScrDateTok invalid = {SCR_DT_INVALID, 0, -1}; + if (scr_date_tok_sign(in->next)) { + ScrDateTok sign = scr_date_next(in); + if (!scr_date_tok_fixed(in->next, 6)) return sign; + int s = 44 - sign.value; + int year = scr_date_next(in).value; + if (s < 0 && year == 0) return sign; + scr_date_day_add(day, s * year); + } else if (scr_date_tok_fixed(in->next, 4)) { + scr_date_day_add(day, scr_date_next(in).value); + } else { + return scr_date_next(in); + } + if (scr_date_skip(in, '-')) { + if (!scr_date_tok_fixed(in->next, 2) || !scr_date_between(in->next.value, 1, 12)) { + return scr_date_next(in); + } + scr_date_day_add(day, scr_date_next(in).value); + if (scr_date_skip(in, '-')) { + if (!scr_date_tok_fixed(in->next, 2) || !scr_date_between(in->next.value, 1, 31)) { + return scr_date_next(in); + } + scr_date_day_add(day, scr_date_next(in).value); + } + } + if (in->next.tag != SCR_DK_T) { + if (in->next.tag != SCR_DT_END) return scr_date_next(in); + } else { + scr_date_next(in); + if (!scr_date_tok_fixed(in->next, 2) || !scr_date_between(in->next.value, 0, 24)) return invalid; + bool hour_is_24 = in->next.value == 24; + scr_date_time_add(time, scr_date_next(in).value); + if (!scr_date_skip(in, ':')) return invalid; + if (!scr_date_tok_fixed(in->next, 2) || !scr_date_between(in->next.value, 0, 59) || + (hour_is_24 && in->next.value > 0)) { + return invalid; + } + scr_date_time_add(time, scr_date_next(in).value); + if (scr_date_skip(in, ':')) { + if (!scr_date_tok_fixed(in->next, 2) || !scr_date_between(in->next.value, 0, 59) || + (hour_is_24 && in->next.value > 0)) { + return invalid; + } + scr_date_time_add(time, scr_date_next(in).value); + if (scr_date_skip(in, '.')) { + if (in->next.tag != SCR_DT_NUMBER || (hour_is_24 && in->next.value > 0)) return invalid; + scr_date_time_add(time, scr_date_millis(scr_date_next(in))); + } + } + if (scr_date_tok_z(in->next)) { + scr_date_next(in); + scr_date_zone_set(tz, 0); + } else if (scr_date_tok_sign(in->next)) { + tz->sign = scr_date_next(in).value == '+' ? 1 : -1; + if (scr_date_tok_fixed(in->next, 4)) { + int hourmin = scr_date_next(in).value; + int hour = hourmin / 100, minute = hourmin % 100; + if (!scr_date_between(hour, 0, 23) || !scr_date_between(minute, 0, 59)) return invalid; + tz->hour = hour; + tz->minute = minute; + } else { + if (!scr_date_tok_fixed(in->next, 2) || !scr_date_between(in->next.value, 0, 23)) { + return invalid; + } + tz->hour = scr_date_next(in).value; + if (!scr_date_skip(in, ':')) return invalid; + if (!scr_date_tok_fixed(in->next, 2) || !scr_date_between(in->next.value, 0, 59)) { + return invalid; + } + tz->minute = scr_date_next(in).value; + } + } + if (in->next.tag != SCR_DT_END) return invalid; + } + /* Date-only forms without a zone are UTC; date-times are local. */ + if (tz->hour == SCR_DT_NONE && time->index == 0) scr_date_zone_set(tz, 0); + day->iso = true; + ScrDateTok end = {SCR_DT_END, 0, -1}; + return end; +} + +static bool scr_date_day_write(ScrDateDay *d, double *year_out, double *month_out, double *day_out) { + if (d->index < 1) return false; + while (d->index < 3) d->comp[d->index++] = 1; + int year = 0, month, day; + if (d->named_month == SCR_DT_NONE) { + if (d->iso || !scr_date_between(d->comp[0], 1, 31)) { + year = d->comp[0]; + month = d->comp[1]; + day = d->comp[2]; + } else { + month = d->comp[0]; + day = d->comp[1]; + year = d->comp[2]; + } + } else { + month = d->named_month; + /* V8 pads to three components before choosing an order, so a lone + * day after a month name reads the padding 1 as the year (2001). */ + if (!scr_date_between(d->comp[0], 1, 31)) { + year = d->comp[0]; + day = d->comp[1]; + } else { + day = d->comp[0]; + year = d->comp[1]; + } + } + if (!d->iso) { + if (scr_date_between(year, 0, 49)) year += 2000; + else if (scr_date_between(year, 50, 99)) year += 1900; + } + if (!scr_date_between(month, 1, 12) || !scr_date_between(day, 1, 31)) return false; + *year_out = year; + *month_out = month - 1; + *day_out = day; + return true; +} + +static bool scr_date_time_write(ScrDateTime *t, double out[4]) { + while (t->index < 4) t->comp[t->index++] = 0; + int hour = t->comp[0], minute = t->comp[1], second = t->comp[2], millisecond = t->comp[3]; + if (t->hour_offset != SCR_DT_NONE) { + if (!scr_date_between(hour, 0, 12)) return false; + hour %= 12; + hour += t->hour_offset; + } + if (!scr_date_between(hour, 0, 23) || !scr_date_between(minute, 0, 59) || + !scr_date_between(second, 0, 59) || !scr_date_between(millisecond, 0, 999)) { + if (hour != 24 || minute != 0 || second != 0 || millisecond != 0) return false; + } + out[0] = hour; + out[1] = minute; + out[2] = second; + out[3] = millisecond; + return true; +} + +static bool scr_date_zone_write(ScrDateZone *z, double *offset_seconds) { + if (z->sign == SCR_DT_NONE) { + *offset_seconds = NAN; + return true; + } + if (z->hour == SCR_DT_NONE) z->hour = 0; + if (z->minute == SCR_DT_NONE) z->minute = 0; + unsigned total = (unsigned)z->hour * 3600u + (unsigned)z->minute * 60u; + if (total > (unsigned)INT_MAX) return false; + *offset_seconds = z->sign < 0 ? -(double)total : (double)total; + return true; +} + +static double scr_date_parse_v8(ScrStr *s) { + ScrDateScan in = {(const unsigned char *)s->data, (const unsigned char *)s->data + s->len, 0, 0, {0, 0, 0}}; + scr_date_scan_advance(&in); + in.next = scr_date_scan_token(&in); + ScrDateDay day = {{0, 0, 0}, 0, SCR_DT_NONE, false}; + ScrDateTime time = {{0, 0, 0, 0}, 0, SCR_DT_NONE}; + ScrDateZone tz = {SCR_DT_NONE, SCR_DT_NONE, SCR_DT_NONE}; + ScrDateTok token = scr_date_parse_es5(&in, &day, &time, &tz); + if (token.tag == SCR_DT_INVALID) return NAN; + bool has_read_number = day.index != 0; + for (; token.tag != SCR_DT_END; token = scr_date_next(&in)) { + if (token.tag == SCR_DT_NUMBER) { + has_read_number = true; + int n = token.value; + if (scr_date_skip(&in, ':')) { + if (scr_date_skip(&in, ':')) { + /* n:: */ + if (time.index != 0) return NAN; + scr_date_time_add(&time, n); + scr_date_time_add(&time, 0); + } else { + if (!scr_date_time_add(&time, n)) return NAN; + if (scr_date_tok_symbol(in.next, '.')) scr_date_next(&in); + } + } else if (scr_date_skip(&in, '.') && scr_date_time_expecting(&time, n)) { + scr_date_time_add(&time, n); + if (in.next.tag != SCR_DT_NUMBER) return NAN; + int ms = scr_date_millis(scr_date_next(&in)); + if (ms < 0) return NAN; + scr_date_time_add_final(&time, ms); + } else if (scr_date_zone_expecting(&tz, n)) { + tz.minute = n; + } else if (scr_date_time_expecting(&time, n)) { + scr_date_time_add_final(&time, n); + ScrDateTok peek = in.next; + if (peek.tag != SCR_DT_END && peek.tag != SCR_DT_SPACE && !scr_date_tok_z(peek) && + !scr_date_tok_sign(peek)) { + return NAN; + } + } else { + if (!scr_date_day_add(&day, n)) return NAN; + scr_date_skip(&in, '-'); + } + } else if (token.tag >= 0) { + if (token.tag == SCR_DK_AMPM && time.index != 0) { + time.hour_offset = token.value; + } else if (token.tag == SCR_DK_MONTH) { + day.named_month = token.value; + scr_date_skip(&in, '-'); + } else if (token.tag == SCR_DK_ZONE && has_read_number) { + scr_date_zone_set(&tz, token.value); + } else { + /* Garbage words are illegal once a number has been read, and the + * first number must be separated from them. */ + if (has_read_number) return NAN; + if (in.next.tag == SCR_DT_NUMBER) return NAN; + } + } else if (scr_date_tok_sign(token) && + ((tz.hour == 0 && tz.minute == 0) || time.index != 0)) { + /* A UTC offset, only after UTC or a time. */ + tz.sign = token.value == '-' ? -1 : 1; + int n = 0, length = 0; + if (in.next.tag == SCR_DT_NUMBER) { + ScrDateTok number = scr_date_next(&in); + length = number.length; + n = number.value; + } + has_read_number = true; + if (scr_date_tok_symbol(in.next, ':')) { + tz.hour = n; + tz.minute = SCR_DT_NONE; + } else if (length == 2 || length == 1) { + tz.hour = n; + tz.minute = 0; + } else if (length == 4 || length == 3) { + tz.hour = n / 100; + tz.minute = n % 100; + } else { + return NAN; + } + } else if ((scr_date_tok_sign(token) || scr_date_tok_symbol(token, ')')) && has_read_number) { + return NAN; + } + /* Anything else (whitespace, unknown characters) is ignored. */ + } + double year, month, date, hms[4], offset; + if (!scr_date_day_write(&day, &year, &month, &date) || !scr_date_time_write(&time, hms) || + !scr_date_zone_write(&tz, &offset)) { + return NAN; + } + double dayv = scr_date_v8_make_day(year, month, date); + double timev = scr_date_v8_make_time(hms[0], hms[1], hms[2], hms[3]); + if (isnan(offset)) return scr_date_from_local(dayv, timev); + if (!isfinite(dayv) || !isfinite(timev)) return NAN; + double t = timev + dayv * 86400000.0 - offset * 1000.0; + if (!(t >= -8640000000000000.0 && t <= 8640000000000000.0)) return NAN; + return scr_date_new_ms(t); +} + /* ── Number statics ──────────────────────────────────────────────────── * JS-exact: the ES2015 Number statics never coerce (unlike the global * isNaN/isFinite), and the compiler routes only number-typed arguments diff --git a/packages/runtime/src/scr_number.h b/packages/runtime/src/scr_number.h index 84db27075..80911023e 100644 --- a/packages/runtime/src/scr_number.h +++ b/packages/runtime/src/scr_number.h @@ -101,8 +101,9 @@ double scr_date_get_time(double ms); * 0–9999). THROWS Node's "Invalid time value" RangeError on NaN or * |ms| > 8.64e15 and returns NULL; +1 otherwise. */ ScrStr *scr_date_to_iso(double ms); -/* new Date(dateString).getTime(): the BOUNDED parse (the X509 validity - * shape + ECMA's format with an explicit offset); NaN elsewhere. */ +/* new Date(dateString).getTime() and Date.parse: V8's date parser (the + * ES5 format, then its legacy grammar: RFC 1123/2822, Date#toString, + * "Jan 2, 2024", ...). Zone-less dates are local time. Never throws. */ double scr_date_parse_get_time(ScrStr *s); /* Date.UTC over already-number arguments (frontend completes the spec's * defaults): MakeDay/MakeTime/TimeClip exactly — 0–99 maps to 1900+year, diff --git a/tests/corpus/6230-date-parse-legacy.ts b/tests/corpus/6230-date-parse-legacy.ts new file mode 100644 index 000000000..fdf4a5bcd --- /dev/null +++ b/tests/corpus/6230-date-parse-legacy.ts @@ -0,0 +1,112 @@ +// Date.parse and new Date(string) follow V8's date-string grammar: the ES5 +// date-time format first, then the legacy forms Node accepts (RFC 1123 and +// RFC 2822 HTTP dates, Date#toString output, month names, slashes, AM/PM, +// zone names and numeric offsets). Strings without a zone are local time, +// so every input is parsed under several zones, including DST transitions. +const fixed = [ + "Mon, 01 Jan 2024 00:00:00 GMT", + "Sun, 06 Nov 1994 08:49:37 GMT", + "Sunday, 06-Nov-94 08:49:37 GMT", + "Sun Nov 6 08:49:37 1994", + "Tue, 2 Jan 2024 03:04:05 +0100", + "2 Jan 2024 03:04 -0800", + "Mon Jan 01 2024 00:00:00 GMT+0000 (Coordinated Universal Time)", + "Thu Jan 01 1970 00:00:00 GMT-0500 (EST)", + "Jan 5", + "1/2", + "1/2/3", + "2024/01/02", + "2024/01/02 10:00", + "2024-01-02 10:00:00", + "2024-01-02T10:00:00", + "2024-01-02T10:00:00.5", + "2024-01-02T10:00:00.123456Z", + "2024-01-02T10:00:00+0530", + "2024-01-02T24:00:00Z", + "2024-01-02T24:00:01Z", + "2024-01-02T1:00Z", + " 2024-01-01", + "2024-01-01 ", + "Jan 2, 2024", + "January 2, 2024 10:00 PM", + "12:00 am Jan 1 2024", + "12:00 pm Jan 1 2024", + "13:00 pm Jan 1 2024", + "Jan 1 2024 10:00 GMT+5", + "Jan 1 2024 10:00 UTC+0530", + "Jan 1 2024 10:00 +05:30", + "Jan 1 2024 10:00 PST", + "Jan 1 2024 10:00 edt", + "Jan 1 2024 10:00 XYZ", + "Jan 1 2024 10.30", + "10:20:30 Jan 1 2024", + "Jan 1 2024 10:: GMT", + "Jan 1 2024 (a (nested) comment) 10:00", + "Jan 1 2024 10:00)", + "foo 2024-01-01", + "foo2024", + "May 2024", + "2024 May 3", + "3 May 2024", + "May 3 99", + "May 3 49", + "May 3 50", + "Feb 29 2023", + "Feb 30 2024 GMT", + "Dec 31 1969 23:59:59.999 GMT", + "2024-13-01", + "2024-02-31T00:00:00Z", + "+002024-01-01", + "-000000-01-01", + "-000001-01-01T00:00:00Z", + "+275760-09-13T00:00:00.000Z", + "+275760-09-13T00:00:00.001Z", + "Sat, 13 Sep 275760 00:00:00 GMT", + "Sat, 13 Sep 275760 00:00:01 GMT", + "-271821-04-20T00:00:00Z", + "Jan 1 9999999 GMT", + "2024-01-01T10:00:00\u0000junk", + "Jan 1
2024", + "Jan 1 2024", + "Jan 1 2024 été", + "0", + "12", + "2024", + "20240", + "", + "garbage", +]; +// A deterministic generator of date-like strings over V8's token classes. +let seed = 20240101; +function next(n: number): number { + seed = (seed * 1103515245 + 12345) % 2147483648; + return seed % n; +} +const pieces = ["Mon", "Tue,", "Wednesday", "Jan", "january", "FEB", "Sept", "dec", "ma", "1", "01", "2", "12", "13", "24", "31", "32", "59", "60", "99", "100", "2024", "1970", "0", "000", "0000", "123456", "-", "+", ":", "::", ".", ",", "/", " ", "\t", "(", ")", "(x)", "GMT", "UTC", "UT", "Z", "T", "t", "PST", "edt", "AM", "pm", "+0100", "-0800", "+01:00", "-8", "GMT+2", "GMT-0530", "999", "1000000", "x", "10:00", "23:59:59", "24:00", "12:30:45.123", "2024-01-15", "2024-01-15T10:00", "T10:00:00Z", "Jan1", "1Jan"]; +const generated: string[] = []; +for (let i = 0; i < 1500; i++) { + let s = ""; + const n = 1 + next(6); + for (let j = 0; j < n; j++) s += pieces[next(pieces.length)]! + (next(3) === 0 ? " " : ""); + generated.push(s); +} +for (const zone of ["UTC", "America/New_York", "Asia/Kolkata", "Australia/Lord_Howe"]) { + process.env.TZ = zone; + console.log("zone", zone); + for (const s of fixed) console.log(JSON.stringify(s), Date.parse(s), new Date(s).getTime()); + let valid = 0; + let sum = 0; + let hash = 0; + for (const s of generated) { + const t = Date.parse(s); + if (Number.isNaN(t)) continue; + valid++; + sum = (sum + (t % 1000003)) % 1000000007; + hash = (hash * 31 + (t % 65521)) % 2147483647; + } + console.log("generated", generated.length, "valid", valid, sum, hash); +} +// An HTTP conditional GET (the fresh package's comparison). +const lastModified = "Sun, 31 Dec 2023 00:00:00 GMT"; +const ifModifiedSince = "Mon, 01 Jan 2024 00:00:00 GMT"; +console.log("fresh", Date.parse(lastModified) <= Date.parse(ifModifiedSince)); diff --git a/tests/coverage-fixtures/divergences.ts b/tests/coverage-fixtures/divergences.ts index e13701a93..43c32a738 100644 --- a/tests/coverage-fixtures/divergences.ts +++ b/tests/coverage-fixtures/divergences.ts @@ -47,7 +47,7 @@ function sizeOf(s: Shape): number { } console.log(sizeOf(new Circle())); -// The native date parser takes ISO 8601 with an explicit offset. +// Date strings parse with V8's grammar natively, so none of these diverge. console.log(Date.parse("Jan 2, 2024"), new Date("2024/01/02").getTime(), Date.parse("2024-01-02T03:04:05Z")); const stamps = ["2024-03-04T05:06:07Z", "March 4, 2024"]; for (const stamp of stamps) console.log(Date.parse(stamp)); diff --git a/tests/harness/__snapshots__/coverage-divergences.txt b/tests/harness/__snapshots__/coverage-divergences.txt index 67c9b57e3..0b261f3d0 100644 --- a/tests/harness/__snapshots__/coverage-divergences.txt +++ b/tests/harness/__snapshots__/coverage-divergences.txt @@ -5,7 +5,7 @@ scriptc coverage tests/coverage-fixtures/divergences.ts fully static — all analyzed statements compile to native code. - differs from Node 8 sites (compiles; the native program can behave differently) + differs from Node 5 sites (compiles; the native program can behave differently) ×1 SC6001 passing a 'Tagged' where 'Labeled' is expected copies the object (converting to a record type with other properties compiles as a field copy): the write to 'target.label' updates only the copy, while… at tests/coverage-fixtures/divergences.ts:16:9 hint: declare the parameter or binding with the value's full type ('Tagged'), or make the shape a class — class instances keep their identity when passed as a base class @@ -20,13 +20,4 @@ scriptc coverage tests/coverage-fixtures/divergences.ts hint: results agree with Node for Latin-script text; for other scripts compare explicitly (for example by code point with < and >) so both runtimes agree ×1 SC6004 this 'Circle' reaches a cast to the unrelated class 'Square' in the callee: natively the checked cast throws a TypeError when it executes, while Node reads the members structurally at tests/coverage-fixtures/divergences.ts:48:20 - hint: narrow with 'instanceof Square' before casting, or cast to a base class or interface both classes share - ×1 SC6005 the date string 'Jan 2, 2024' parses to an invalid date (NaN) natively, while Node accepts it (the native parser takes ISO 8601 date-times with an explicit offset, such as '2024-01-02T03:04:05Z', and… - at tests/coverage-fixtures/divergences.ts:51:24 - hint: write the date in ISO 8601 with an explicit offset ('Z' or '+HH:MM'), or build it from numbers with Date.UTC - ×1 SC6005 the date string '2024/01/02' parses to an invalid date (NaN) natively, while Node accepts it (the native parser takes ISO 8601 date-times with an explicit offset, such as '2024-01-02T03:04:05Z', and … - at tests/coverage-fixtures/divergences.ts:51:49 - hint: write the date in ISO 8601 with an explicit offset ('Z' or '+HH:MM'), or build it from numbers with Date.UTC - ×1 SC6005 the date string 'March 4, 2024' parses to an invalid date (NaN) natively, while Node accepts it (the native parser takes ISO 8601 date-times with an explicit offset, such as '2024-01-02T03:04:05Z', a… - at tests/coverage-fixtures/divergences.ts:52:41 - hint: write the date in ISO 8601 with an explicit offset ('Z' or '+HH:MM'), or build it from numbers with Date.UTC \ No newline at end of file + hint: narrow with 'instanceof Square' before casting, or cast to a base class or interface both classes share \ No newline at end of file diff --git a/tests/harness/coverage.test.ts b/tests/harness/coverage.test.ts index 06f0e75a8..c7ba05248 100644 --- a/tests/harness/coverage.test.ts +++ b/tests/harness/coverage.test.ts @@ -46,9 +46,6 @@ test("divergences report as warnings, never as blockers", async () => { "SC6002", "SC6003", "SC6004", - "SC6005", - "SC6005", - "SC6005", ]); expect(coveragePasses(coverage, "blockers")).toBe(true); expect(coveragePasses(coverage, "divergences")).toBe(false); @@ -220,11 +217,11 @@ test("CLI: build --print=diagnostics reports failures and divergence warnings as }; expect(envelope.success).toBe(true); expect(envelope.artifact).toBe(join(outDir, "out.ir.json")); - expect(envelope.diagnostics.map((d) => d.severity)).toEqual(Array(8).fill("warning")); + expect(envelope.diagnostics.map((d) => d.severity)).toEqual(Array(5).fill("warning")); const human = build(fixture("divergences.ts")); expect(human.status).toBe(0); expect(human.stderr).toContain("warning SC6001"); - expect(human.stderr).toContain("8 warnings: the program compiled"); + expect(human.stderr).toContain("5 warnings: the program compiled"); } finally { rmSync(outDir, { recursive: true, force: true }); }