| 1 |
# DateTime Field Bag Design |
| 2 |
|
| 3 |
## Background & Motivation |
| 4 |
|
| 5 |
In ECMA-402 (`Intl.DateTimeFormat`), a formatting request is constructed from a set of user-specified options. These options represent a mix of different concerns, which are split in a compliant implementation: |
| 6 |
|
| 7 |
1. **Field-related options** (e.g., `year`, `month`, `day`, `hour`): These capture the user's choices for field selection and widths. They are mapped to `DateTimeFieldBag` (and subsequently converted to a `FieldSet` via the bridge). |
| 8 |
2. **Policy-related options** (e.g., `numberingSystem`, `hourCycle`, `calendar`): These represent broader formatter policy and are passed to the formatter via `DateTimeFormatterPreferences`. |
| 9 |
3. **Locale matching options** (e.g., `localeMatcher`): These are handled during locale negotiation beforehand and do not reach the formatter. |
| 10 |
|
| 11 |
### Goals |
| 12 |
|
| 13 |
* Provide a human-readable, machine-parseable representation of datetime field requests. |
| 14 |
* Model the common ECMA-402 / ICU4C datetime field subset. |
| 15 |
* Keep the type focused on fields and field widths, not on other formatter options. |
| 16 |
* Make round-tripping through a UTS 35 skeleton string lossless for the supported subset. |
| 17 |
* Make conversion to `FieldSetBuilder` possible even when it is not exact. |
| 18 |
|
| 19 |
### Non-Goals |
| 20 |
|
| 21 |
* Stock pattern presets (namely, the `dateStyle` and `timeStyle` presets: `Full`, `Long`, `Medium`, and `Short`), as opposed to individual field widths (like `month: "long"` or `weekday: "short"`). |
| 22 |
* Locale negotiation (such as the ECMA-402 `localeMatcher` option), which is not handled by ICU4X. |
| 23 |
* Hour-cycle preferences. |
| 24 |
* Numbering system preferences. |
| 25 |
* A full replacement for the existing `fieldsets` API. |
| 26 |
* A perfect round-trip between the bag and `FieldSetBuilder`. |
| 27 |
|
| 28 |
## Proposed Solution |
| 29 |
|
| 30 |
We propose a new module, `fieldbag`, centered around the `DateTimeFieldBag` struct. |
| 31 |
|
| 32 |
The architecture is built around a 4-step mental model that defines how a formatting request flows into the ICU4X formatting pipeline: |
| 33 |
|
| 34 |
1. **`DateTimeFieldBag`** (Raw Request): Captures the fine-grained field presence and width choices from the user. |
| 35 |
* *Example:* A request for "wide month and two-digit year", represented as `{ year: TwoDigit, month: Long }`. |
| 36 |
2. **UTS 35 Skeleton String** (Interchange Format): The precise, lossless wire format for the raw request (e.g., `yyMMMM`). |
| 37 |
3. **`FieldSetBuilder`** (The Bridge): A helper that takes a detailed `DateTimeFieldBag` (or its skeleton) and maps it to the closest matching ICU4X formatting category, collapsing widths if necessary. |
| 38 |
* *Example:* Maps the `yyMMMM` request to a `YM` fieldset. |
| 39 |
4. **`CompositeFieldSet`** (Resolved Category): The concrete, optimized runtime enum that wraps the resolved category (e.g., wrapping a `DateFieldSet::YM`). This is a downstream choice, not the core representation of the request. |
| 40 |
|
| 41 |
`DateTimeFieldBag` is a flat struct of optional fields, where each field represents a requested datetime component and its desired width. It acts as a clean, intermediate representation of a user's formatting request. |
| 42 |
|
| 43 |
### Suggested API Surface |
| 44 |
|
| 45 |
We recommend explicit, named methods for conversion and standard traits for serialization, making the lossy nature of the conversions clear: |
| 46 |
|
| 47 |
* `impl writeable::Writeable for DateTimeFieldBag` (enables canonical skeleton serialization) |
| 48 |
* `impl std::str::FromStr for DateTimeFieldBag` (strict parser using UTS 35 skeleton syntax) |
| 49 |
* `type Err = DateTimeFieldBagParseError` |
| 50 |
* `impl DateTimeFieldBag` |
| 51 |
* `pub fn to_string(&self) -> String` (convenience wrapper shadowing `ToString::to_string` for high-performance serialization) |
| 52 |
* `pub fn try_from_skeleton(s: &str) -> Result<Self, DateTimeFieldBagParseError>` (explicit, self-documenting named constructor that delegates to `FromStr`) |
| 53 |
* `pub fn to_field_set_builder(&self) -> FieldSetBuilder` (lossy conversion) |
| 54 |
* `pub fn from_field_set_builder(builder: &FieldSetBuilder) -> Self` (best-effort reconstruction) |
| 55 |
|
| 56 |
### Module Shape |
| 57 |
|
| 58 |
The module name should be `fieldbag` in flat case, matching ICU4X's existing module naming style. |
| 59 |
This avoids the overloaded word `components`, which already means something else in ICU4X. |
| 60 |
|
| 61 |
The type name should be `DateTimeFieldBag`. |
| 62 |
|
| 63 |
The module should be public as `icu_datetime::fieldbag`. |
| 64 |
It may reuse `provider::fields` internally, but it should not be a provider-only module. |
| 65 |
|
| 66 |
### Data Model |
| 67 |
|
| 68 |
`DateTimeFieldBag` is a struct of optional fields, not an ordered list. |
| 69 |
Each field captures the field family and its width choice. |
| 70 |
|
| 71 |
The initial bag should cover ECMA-402 `Intl.DateTimeFormat` field options that map naturally to |
| 72 |
UTS 35 skeleton syntax: |
| 73 |
|
| 74 |
- era |
| 75 |
- year |
| 76 |
- month |
| 77 |
- day |
| 78 |
- weekday |
| 79 |
- day period |
| 80 |
- hour |
| 81 |
- minute |
| 82 |
- second |
| 83 |
- subsecond |
| 84 |
- time zone name |
| 85 |
|
| 86 |
The bag does not carry: |
| 87 |
|
| 88 |
- hour cycle preference, including the current `components::Bag::hour_cycle` field |
| 89 |
- numbering system preference |
| 90 |
- year style preference |
| 91 |
- other formatter-level knobs that belong to `FieldSetBuilder` |
| 92 |
|
| 93 |
## String Serialization (UTS 35 Skeletons) |
| 94 |
|
| 95 |
The primary exact interchange format for `DateTimeFieldBag` is a string using UTS 35 classical skeleton syntax for the representable subset. |
| 96 |
|
| 97 |
* **Serialization:** String output must use ICU4X `Writeable`, not `Display`. The serialization always produces a canonicalized string, meaning the same bag state always serializes to the same skeleton string. |
| 98 |
* **Parsing:** Parsing uses the `FromStr` trait (returning `DateTimeFieldBagParseError`) or the `try_from_skeleton` helper. The parser must be strict and reject unsupported syntax rather than guessing. |
| 99 |
|
| 100 |
### Constraints |
| 101 |
|
| 102 |
* The string syntax must be canonicalized on output. |
| 103 |
* Parsing must reject unsupported syntax, returning `DateTimeFieldBagParseError`. |
| 104 |
* **Parsing must reject explicit hour cycle symbols (`h`, `H`, `K`, `k`).** Skeletons containing these symbols must fail to parse. |
| 105 |
* If a UTS 35 string contains information the bag cannot represent, the parse must fail. |
| 106 |
|
| 107 |
### Representative Mappings |
| 108 |
|
| 109 |
| Bag concept | Skeleton form | |
| 110 |
|---|---| |
| 111 |
| year numeric / two-digit | `y` / `yy` | |
| 112 |
| month numeric / two-digit | `M` / `MM` | |
| 113 |
| month abbreviated / wide / narrow | `MMM` / `MMMM` / `MMMMM` | |
| 114 |
| era short / wide / narrow | `G` / `GGGG` / `GGGGG` | |
| 115 |
| weekday short / wide / narrow | `E` / `EEEE` / `EEEEE` | |
| 116 |
| day numeric / two-digit | `d` / `dd` | |
| 117 |
| day period with hour | `C` family, with width determined by day-period style and hour padding | |
| 118 |
| day period without hour | `a` / `b` / `B` family (depending on style/width) | |
| 119 |
| hour numeric / two-digit | `j` / `jj` unless an explicit day-period field requires the `C` family | |
| 120 |
| minute numeric / two-digit | `m` / `mm` | |
| 121 |
| second numeric / two-digit | `s` / `ss` | |
| 122 |
| fractional second digits | repeated `S` | |
| 123 |
| time zone name | supported `z`, `O`, and `v` forms | |
| 124 |
|
| 125 |
### Hour and Day Period Representation |
| 126 |
|
| 127 |
The hour and day period fields are mapped to UTS 35 skeleton symbols to avoid introducing hour-cycle preferences into the bag, while still supporting standalone day periods. |
| 128 |
|
| 129 |
* **Hour-only requests:** Serialized using `j` (numeric) or `jj` (two-digit). |
| 130 |
* **Requests with hour and day period:** Serialized using the `C` family, which encodes both the hour padding and the day-period width (e.g., `C`/`CC` for abbreviated, `CCC`/`CCCC` for wide, `CCCCC`/`CCCCCC` for narrow). |
| 131 |
* **Requests with day period only (no hour):** Serialized using the `a`/`b`/`B` family depending on the requested day-period style (abbreviated/wide/narrow). |
| 132 |
|
| 133 |
**Standalone Day Period Handling:** |
| 134 |
* The skeleton parser **accepts** standalone day period symbols (`a`, `b`, `B`) and parses them into a `DateTimeFieldBag` with `day_period` set and `hour` unset. This ensures lossless round-tripping. |
| 135 |
* During conversion to `FieldSetBuilder` (`to_field_set_builder`), a standalone day period is not supported by the underlying dynamic fieldsets and will be rejected or normalized (best-effort). |
| 136 |
|
| 137 |
|
| 138 |
## Conversion from DateTimeFieldBag to FieldSetBuilder |
| 139 |
|
| 140 |
Conversion from `DateTimeFieldBag` to `FieldSetBuilder` is best-effort and lossy. It should not fail; when there is no exact mapping, it should choose a documented representative builder state. |
| 141 |
|
| 142 |
While this lossy conversion is compliant with the ECMA-402 specification, it may introduce web compatibility issues in cases where different fields request different lengths (e.g., a wide month but an abbreviated weekday). We plan to investigate the scope of these web-compat risks under [CLDR-19550](https://unicode-org.atlassian.net/browse/CLDR-19550). If the risks are too high, our fallback plan is to enhance `FieldSetBuilder` (and the underlying formatting layer) to support more granular, per-field length hints, allowing it to honor mixed-width requests without collapsing them into a single coarse `Length`. |
| 143 |
|
| 144 |
### What gets preserved |
| 145 |
|
| 146 |
The conversion preserves the closest meaningful mapping for: |
| 147 |
* Overall date vs. time vs. date+time shape. |
| 148 |
* Common numeric widths. |
| 149 |
* Common text widths. |
| 150 |
* Supported time-zone styles. |
| 151 |
|
| 152 |
### What gets approximated or omitted |
| 153 |
|
| 154 |
* **Width Simplification:** Narrow month and weekday widths collapse into a broader `Length` choice. |
| 155 |
* **Alignment/Padding:** Field-specific 2-digit (padded) width choices map to a builder-wide `Alignment::Column` preference. *(Rationale: In the `fieldsets` model, `Alignment::Column` is the primary mechanism to support 2-digit numeric fields, as column/tabular alignment is the main driver for developers opting into 2-digit widths. This mapping correctly captures this developer intent.)* |
| 156 |
* **Time Precision:** Minute-only or second-only requests are promoted to a normal time fieldset with the closest `TimePrecision`. |
| 157 |
* **Day Period:** Day period requests without an hour are rejected as invalid. |
| 158 |
* **Settings with no bag equivalent:** `TimePrecision::MinuteOptional` and other non-field builder options remain unset. |
| 159 |
|
| 160 |
### `YearStyle` Forward Resolution |
| 161 |
|
| 162 |
Since `FieldSetBuilder` controls year width via a combination of `Length` and `YearStyle`, while the bag controls it via direct field widths, we resolve the mapping as follows: |
| 163 |
* `year: Some(Year::Numeric)` $\rightarrow$ Maps to `YearStyle::Auto`. The builder's `length` will be guided towards `Length::Medium` or `Length::Long` to prefer full year display. |
| 164 |
* `year: Some(Year::TwoDigit)` $\rightarrow$ Maps to `YearStyle::Auto`. The builder's `length` will be guided towards `Length::Short` to prefer 2-digit display. |
| 165 |
* `era: Some(...)` $\rightarrow$ Maps to `YearStyle::WithEra` (overriding the `Auto` choice above to ensure era is displayed). |
| 166 |
* `era: None` $\rightarrow$ Maps to `YearStyle::Auto` (relying on locale defaults for era display). |
| 167 |
|
| 168 |
The conversion should be documented as a reconstruction aid, not as a stable interchange format. |
| 169 |
|
| 170 |
## Conversion from FieldSetBuilder to DateTimeFieldBag |
| 171 |
|
| 172 |
Conversion from `FieldSetBuilder` back to `DateTimeFieldBag` is also best-effort and inherently lossy, as the builder stores category-level decisions and auxiliary options, while the bag stores field-level choices. It should not fail; the result should be a documented representative bag for the builder state. |
| 173 |
|
| 174 |
### Compromises in this direction |
| 175 |
|
| 176 |
* A single builder `Length` value must be expanded into concrete field widths. |
| 177 |
* `Alignment::Column` in the builder implies that numeric fields in the reconstructed bag should prefer 2-digit (padded) widths (e.g., `yy`, `MM`, `dd`) to preserve the alignment intent. |
| 178 |
* `TimePrecision::MinuteOptional` must become a static field bag (likely hour+minute), losing the input-dependent optionality. |
| 179 |
* Builder defaults may need to be materialized into explicit bag values. |
| 180 |
* Zone styles must be mapped only where the bag supports a corresponding representation. |
| 181 |
|
| 182 |
### `YearStyle` Mapping |
| 183 |
|
| 184 |
`YearStyle` in the builder is mapped back to a combination of `year` and `era` fields in the reconstructed `DateTimeFieldBag`. Since `YearStyle` controls both century display and era visibility, the mapping is defined as: |
| 185 |
|
| 186 |
* `YearStyle::WithEra` $\rightarrow$ `year: Some(Year::Numeric)`, `era: Some(Text::Short)` |
| 187 |
* `YearStyle::NoEra` $\rightarrow$ `year: Some(Year::Numeric)`, `era: None` |
| 188 |
* `YearStyle::Full` $\rightarrow$ `year: Some(Year::Numeric)`, `era: None` (leaves era unset, see note below) |
| 189 |
* `YearStyle::Auto` $\rightarrow$ `year: Some(Year::TwoDigit)` (or `Numeric` depending on length), `era: None` (leaves era unset) |
| 190 |
|
| 191 |
*Note on Era Display:* For `Full` and `Auto`, the era is left unset (`None`) in the bag. We recommend linking this behavior to future improvements in the [TC39 Intl.eraDisplay proposal](https://github.com/tc39/proposal-intl-era-display) for better granularity in the future. |
| 192 |
|
| 193 |
### Recommended rule |
| 194 |
|
| 195 |
The reverse conversion should pick a canonical representative bag for a builder state. That keeps the behavior predictable even when multiple bag shapes could correspond to the same builder. |
| 196 |
|
| 197 |
## Design Decisions & Alternatives Considered |
| 198 |
|
| 199 |
### Why keep `fieldbag` separate from `fieldsets` |
| 200 |
|
| 201 |
- It keeps the user-facing field request model small and focused. |
| 202 |
- It avoids mixing formatter presets and field-level syntax. |
| 203 |
- It keeps the lossless string form independent from dynamic fieldset construction. |
| 204 |
- It prevents the module from becoming a catch-all for datetime formatting policy. |
| 205 |
|
| 206 |
### Why convert via `FieldSetBuilder` instead of directly to/from `CompositeFieldSet` |
| 207 |
|
| 208 |
We rejected making `CompositeFieldSet` the direct source/target of `DateTimeFieldBag` conversion. |
| 209 |
- `CompositeFieldSet` is a concrete runtime formatter input, not a general field request. |
| 210 |
- Converting to it directly would force the broadest dynamic shape even when a caller needs a narrower one. |
| 211 |
- Using `FieldSetBuilder` as the intermediate bridge preserves useful state, allows for better optimization before committing to a final `CompositeFieldSet`, and avoids discarding information about the builder-style intermediate state. |
| 212 |
|
| 213 |
### Why not model stock lengths here |
| 214 |
|
| 215 |
Stock lengths such as `Full`, `Long`, `Medium`, and `Short` are a higher-level preset system. |
| 216 |
They expand into fieldsets and sometimes inject non-bag policy, such as time-zone style. |
| 217 |
They should live in a separate layer. |
| 218 |
|
| 219 |
### Module Naming Alternatives Rejected |
| 220 |
|
| 221 |
We considered and rejected the following names for the new module: |
| 222 |
* **`components`**: Already used to describe the ICU4X crate collection. |
| 223 |
* **`skeleton`**: Exposes an internal standard term that many users will not know (though the string form remains the wire format). |
| 224 |
* **`pattern`**: ICU4X already uses `pattern` for other datetime concepts. |
| 225 |
* **`fieldset`**: `fieldsets` already has a distinct meaning in ICU4X. |
| 226 |
* **`options`**: The bag is not a complete formatter options object. |
| 227 |
|
| 228 |
## Future Work |
| 229 |
|
| 230 |
- Add the stock pattern preset layer for `Full` / `Long` / `Medium` / `Short`. |
| 231 |
- Decide whether the bag should support more UTS 35 symbols over time, such as week fields, day-of-year, or modified Julian day. |
| 232 |
- Decide whether to support `J`, the UTS 35 input skeleton symbol for locale-preferred hour without a day-period marker. This is not part of the initial ECMA-oriented model. |
| 233 |
- Consider whether a public helper should expose conversion to narrower dynamic fieldset types, not only `FieldSetBuilder`. |
| 234 |
- Add tests that verify the intended exact and best-effort properties: |
| 235 |
- bag -> string -> bag |
| 236 |
- bag -> builder produces the expected closest `FieldSetBuilder` |
| 237 |
- builder -> bag produces the expected representative `DateTimeFieldBag` |
| 238 |
- formatter -> builder -> formatter |
| 239 |
|
| 240 |
## Implementation Notes |
| 241 |
|
| 242 |
The implementation should stay close to the existing ICU4X datetime architecture: |
| 243 |
|
| 244 |
- implement and expose the bag from `icu_datetime::fieldbag` |
| 245 |
- reuse provider field primitives only when they fit the public fieldbag contract |
| 246 |
- use `Writeable` for string output, not `Display` |
| 247 |
- keep parsing logic explicit and conservative |
| 248 |
- reuse existing `FieldSetBuilder` conversion helpers where possible |
| 249 |
- avoid coupling the bag to locale fallback or formatter selection logic |