Skip to main content

atmos/os_lib/ecma/builtins/
intl.rs

1//! `Intl` (ECMAScript Internationalization API Specification) 実装。
2//!
3//! `Intl.NumberFormat`, `Intl.DateTimeFormat`, `Intl.Collator`, `Intl.PluralRules`,
4//! `Intl.RelativeTimeFormat`, `Intl.Segmenter`, `Intl.ListFormat`, `Intl.DisplayNames`,
5//! および `Intl.getCanonicalLocales` を提供する。
6
7use super::*;
8use alloc::format;
9use alloc::rc::Rc;
10use alloc::string::{String, ToString};
11use alloc::vec;
12use alloc::vec::Vec;
13
14/// `Intl` グローバルオブジェクトを作成して返す。
15pub(crate) fn create_intl_object() -> Value {
16    let intl = Obj::plain();
17
18    // Intl.getCanonicalLocales(locales)
19    intl.borrow_mut().props.insert(
20        "getCanonicalLocales".into(),
21        nv("Intl.getCanonicalLocales", intl_get_canonical_locales),
22    );
23
24    // Intl.NumberFormat
25    let number_format = create_intl_constructor(
26        "NumberFormat",
27        intl_number_format_ctor,
28        vec![
29            ("format", intl_number_format_format),
30            ("formatToParts", intl_number_format_format_to_parts),
31            ("resolvedOptions", intl_number_format_resolved_options),
32        ],
33    );
34    intl.borrow_mut().props.insert("NumberFormat".into(), number_format);
35
36    // Intl.DateTimeFormat
37    let datetime_format = create_intl_constructor(
38        "DateTimeFormat",
39        intl_datetime_format_ctor,
40        vec![
41            ("format", intl_datetime_format_format),
42            ("formatToParts", intl_datetime_format_format_to_parts),
43            ("resolvedOptions", intl_datetime_format_resolved_options),
44        ],
45    );
46    intl.borrow_mut().props.insert("DateTimeFormat".into(), datetime_format);
47
48    // Intl.Collator
49    let collator = create_intl_constructor(
50        "Collator",
51        intl_collator_ctor,
52        vec![
53            ("compare", intl_collator_compare),
54            ("resolvedOptions", intl_collator_resolved_options),
55        ],
56    );
57    intl.borrow_mut().props.insert("Collator".into(), collator);
58
59    // Intl.PluralRules
60    let plural_rules = create_intl_constructor(
61        "PluralRules",
62        intl_plural_rules_ctor,
63        vec![
64            ("select", intl_plural_rules_select),
65            ("resolvedOptions", intl_plural_rules_resolved_options),
66        ],
67    );
68    intl.borrow_mut().props.insert("PluralRules".into(), plural_rules);
69
70    // Intl.RelativeTimeFormat
71    let relative_time_format = create_intl_constructor(
72        "RelativeTimeFormat",
73        intl_relative_time_format_ctor,
74        vec![
75            ("format", intl_relative_time_format_format),
76            ("formatToParts", intl_relative_time_format_format_to_parts),
77            ("resolvedOptions", intl_relative_time_format_resolved_options),
78        ],
79    );
80    intl.borrow_mut().props.insert("RelativeTimeFormat".into(), relative_time_format);
81
82    // Intl.Segmenter
83    let segmenter = create_intl_constructor(
84        "Segmenter",
85        intl_segmenter_ctor,
86        vec![
87            ("segment", intl_segmenter_segment),
88            ("resolvedOptions", intl_segmenter_resolved_options),
89        ],
90    );
91    intl.borrow_mut().props.insert("Segmenter".into(), segmenter);
92
93    // Intl.ListFormat
94    let list_format = create_intl_constructor(
95        "ListFormat",
96        intl_list_format_ctor,
97        vec![
98            ("format", intl_list_format_format),
99            ("formatToParts", intl_list_format_format_to_parts),
100            ("resolvedOptions", intl_list_format_resolved_options),
101        ],
102    );
103    intl.borrow_mut().props.insert("ListFormat".into(), list_format);
104
105    // Intl.DisplayNames
106    let display_names = create_intl_constructor(
107        "DisplayNames",
108        intl_display_names_ctor,
109        vec![
110            ("of", intl_display_names_of),
111            ("resolvedOptions", intl_display_names_resolved_options),
112        ],
113    );
114    intl.borrow_mut().props.insert("DisplayNames".into(), display_names);
115
116    // Intl.DurationFormat
117    let duration_format = create_intl_constructor(
118        "DurationFormat",
119        intl_duration_format_ctor,
120        vec![
121            ("format", intl_duration_format_format),
122            ("formatToParts", intl_duration_format_format_to_parts),
123            ("resolvedOptions", intl_duration_format_resolved_options),
124        ],
125    );
126    intl.borrow_mut().props.insert("DurationFormat".into(), duration_format);
127
128    // Intl.Locale
129    let locale_ctor = super::intl_locale::create_intl_locale_constructor();
130    {
131        let mut ib = intl.borrow_mut();
132        ib.props.insert("Locale".into(), locale_ctor);
133        ib.props.insert("supportedValuesOf".into(), nv("Intl.supportedValuesOf", intl_supported_values_of));
134        ib.props.insert("Symbol(Symbol.toStringTag)".into(), Value::str("Intl"));
135        ib.hide_props(&[
136            "Locale",
137            "getCanonicalLocales",
138            "supportedValuesOf",
139            "NumberFormat",
140            "DateTimeFormat",
141            "Collator",
142            "PluralRules",
143            "RelativeTimeFormat",
144            "Segmenter",
145            "ListFormat",
146            "DisplayNames",
147            "DurationFormat",
148        ]);
149        ib.insert_attr(
150            "Symbol(Symbol.toStringTag)",
151            PropertyAttributes { writable: false, enumerable: false, configurable: true },
152        );
153    }
154
155    Value::Object(intl)
156}
157
158fn create_intl_constructor(
159    name: &str,
160    ctor_fn: NativeFn,
161    methods: Vec<(&'static str, NativeFn)>,
162) -> Value {
163    let hidden = PropertyAttributes { writable: true, enumerable: false, configurable: true };
164    let proto = Obj::plain();
165    let ctor = Obj::native(name, ctor_fn);
166    {
167        let mut pb = proto.borrow_mut();
168        for (m_name, m_fn) in methods {
169            pb.props.insert(m_name.into(), nv(m_name, m_fn));
170            pb.insert_attr(m_name, hidden);
171        }
172        pb.props.insert("constructor".into(), Value::Object(ctor.clone()));
173        pb.insert_attr("constructor", hidden);
174        pb.props.insert("Symbol(Symbol.toStringTag)".into(), Value::Str(Rc::new(format!("Intl.{}", name))));
175        pb.insert_attr(
176            "Symbol(Symbol.toStringTag)",
177            PropertyAttributes { writable: false, enumerable: false, configurable: true },
178        );
179    }
180    {
181        let mut cb = ctor.borrow_mut();
182        cb.props.insert("prototype".into(), Value::Object(proto));
183        cb.insert_attr("prototype", PropertyAttributes { writable: false, enumerable: false, configurable: false });
184        let sup_fn = if name == "Collator" {
185            nv("supportedLocalesOf", intl_collator_supported_locales_of)
186        } else {
187            nv("supportedLocalesOf", intl_supported_locales_of)
188        };
189        cb.props.insert("supportedLocalesOf".into(), sup_fn);
190        cb.hide_props(&["supportedLocalesOf"]);
191    }
192    Value::Object(ctor)
193}
194
195fn intl_supported_values_of(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
196    let key = super::props_methods::to_str_strict(it, arg(a, 0))?;
197    let vals: &[&str] = match key.as_str() {
198        "calendar" => &[
199            "buddhist",
200            "chinese",
201            "coptic",
202            "dangi",
203            "ethioaa",
204            "ethiopic",
205            "gregory",
206            "hebrew",
207            "indian",
208            "islamic-civil",
209            "islamic-tbla",
210            "islamic-umalqura",
211            "iso8601",
212            "japanese",
213            "persian",
214            "roc",
215        ],
216        "collation" => &[
217            "big5han",
218            "compat",
219            "dict",
220            "direct",
221            "ducet",
222            "emoji",
223            "eor",
224            "gb2312",
225            "phonebk",
226            "phonetic",
227            "pinyin",
228            "reformed",
229            "searchjl",
230            "stroke",
231            "trad",
232            "unihan",
233            "zhuyin",
234        ],
235        "currency" => &[
236            "AUD", "BRL", "CAD", "CHF", "CNY", "DKK", "EUR", "GBP", "HKD", "IDR", "INR", "JPY",
237            "KRW", "MXN", "NOK", "NZD", "PLN", "RUB", "SAR", "SEK", "SGD", "THB", "TRY", "TWD",
238            "USD", "ZAR",
239        ],
240        "numberingSystem" => &[
241            "adlm", "ahom", "arab", "arabext", "bali", "beng", "bhks", "brah", "cakm", "cham",
242            "deva", "diak", "fullwide", "gong", "gonm", "gujr", "guru", "hanidec", "hmng", "hmnp",
243            "java", "kali", "khmr", "knda", "lana", "lanatham", "laoo", "latn", "lepc", "limb",
244            "mathbold", "mathdbl", "mathmono", "mathsanb", "mathsans", "mlym", "modi", "mong",
245            "mroo", "mtei", "mymr", "mymrshan", "mymrtlng", "newa", "nkoo", "olck", "orya", "osma",
246            "rohg", "saur", "segment", "shrd", "sind", "sinh", "sora", "sund", "takr", "talu",
247            "tamldec", "telu", "thai", "tibt", "tirh", "vaii", "wara", "wcho",
248        ],
249        "timeZone" => &[
250            "Africa/Cairo",
251            "America/Chicago",
252            "America/Los_Angeles",
253            "America/New_York",
254            "America/Sao_Paulo",
255            "Asia/Bangkok",
256            "Asia/Dubai",
257            "Asia/Hong_Kong",
258            "Asia/Kolkata",
259            "Asia/Seoul",
260            "Asia/Shanghai",
261            "Asia/Singapore",
262            "Asia/Tokyo",
263            "Australia/Sydney",
264            "Europe/Berlin",
265            "Europe/London",
266            "Europe/Moscow",
267            "Europe/Paris",
268            "Pacific/Auckland",
269            "UTC",
270        ],
271        "unit" => &[
272            "acre",
273            "bit",
274            "byte",
275            "celsius",
276            "centimeter",
277            "day",
278            "degree",
279            "fahrenheit",
280            "fluid-ounce",
281            "foot",
282            "gallon",
283            "gigabit",
284            "gigabyte",
285            "gram",
286            "hectare",
287            "hour",
288            "inch",
289            "kilobit",
290            "kilobyte",
291            "kilogram",
292            "kilometer",
293            "liter",
294            "megabit",
295            "megabyte",
296            "meter",
297            "microsecond",
298            "mile",
299            "mile-scandinavian",
300            "milliliter",
301            "millimeter",
302            "millisecond",
303            "minute",
304            "month",
305            "nanosecond",
306            "ounce",
307            "percent",
308            "petabyte",
309            "pound",
310            "second",
311            "stone",
312            "terabit",
313            "terabyte",
314            "week",
315            "yard",
316            "year",
317        ],
318        _ => return Err(it.range_error(format!("Invalid key for Intl.supportedValuesOf: {}", key))),
319    };
320    let arr: Vec<Value> = vals.iter().map(|&s| Value::str(s)).collect();
321    Ok(Value::Object(Obj::array(arr)))
322}
323
324fn intl_collator_supported_locales_of(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
325    let _ = canonicalize_locale_list(it, &arg(a, 0))?;
326    let options = get_options_object(it, &arg(a, 1), false)?;
327    let _ = opt_str(it, &options, "localeMatcher", &["lookup", "best fit"])?;
328    let _ = t;
329    Ok(Value::Object(Obj::array(Vec::new())))
330}
331
332fn intl_supported_locales_of(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
333    let list = canonicalize_locale_list(it, &arg(a, 0))?;
334    let options = get_options_object(it, &arg(a, 1), false)?;
335    let _ = opt_str(it, &options, "localeMatcher", &["lookup", "best fit"])?;
336    let supported: Vec<Value> = list
337        .into_iter()
338        .filter(|tag| {
339            let lang = tag.split('-').next().unwrap_or("");
340            !matches!(lang, "und" | "tlh" | "qfz")
341        })
342        .map(|s| Value::Str(Rc::new(s)))
343        .collect();
344    Ok(Value::Object(Obj::array(supported)))
345}
346
347pub(super) fn ctor_locale(it: &mut Interp, locales: &Value) -> Result<String, Value> {
348    let tag = nf_locale(it, locales)?;
349    Ok(match tag.as_str() {
350        "en" => String::from("en-US"),
351        "ja" => String::from("ja-JP"),
352        "zh" => String::from("zh-CN"),
353        "fr" => String::from("fr-FR"),
354        "de" => String::from("de-DE"),
355        "es" => String::from("es-ES"),
356        _ => tag,
357    })
358}
359
360/// GetOptionsObject(`strict`)/ CoerceOptionsToObject。`null` は TypeError、`strict` では原始値も TypeError。
361pub(super) fn get_options_object(it: &mut Interp, v: &Value, strict: bool) -> Result<Value, Value> {
362    match v {
363        Value::Undefined => Ok(Value::Undefined),
364        Value::Object(_) => Ok(v.clone()),
365        Value::Null => Err(it.type_error("Cannot convert undefined or null to object")),
366        _ if strict => Err(it.type_error("Options must be an object")),
367        _ => Ok(Value::Undefined),
368    }
369}
370
371fn opt_bool(it: &mut Interp, opts: &Value, key: &str) -> Result<Option<bool>, Value> {
372    match opt_obj_get(it, opts, key)? {
373        Value::Undefined => Ok(None),
374        v => Ok(Some(v.truthy())),
375    }
376}
377
378fn slot(this: &Value, key: &str) -> Option<String> {
379    match this {
380        Value::Object(o) => o.borrow().props.get(key).map(|v| v.to_js_string()),
381        _ => None,
382    }
383}
384
385fn set_slot(obj: &super::super::value::ObjRef, key: &str, val: &str) {
386    let mut b = obj.borrow_mut();
387    b.props.insert(key.into(), sv(val));
388    b.hide_props(&[key]);
389}
390
391/// 内部スロット `_intl_type` による型の確認(ブランドチェック)。
392fn require_brand(it: &mut Interp, this: &Value, ty: &str, method: &str) -> Result<(), Value> {
393    if let Value::Object(o) = this {
394        if let Some(Value::Str(s)) = o.borrow().props.get("_intl_type") {
395            if s.as_str() == ty {
396                return Ok(());
397            }
398        }
399    }
400    Err(it.type_error(format!("Method Intl.{}.prototype.{} called on incompatible receiver", ty, method)))
401}
402
403/// `Intl.*` コンストラクタの共通の前処理(`new` の確認・ロケール・options)。
404fn intl_ctor_common(
405    it: &mut Interp,
406    this: Value,
407    a: &[Value],
408    ty: &str,
409    need_new: bool,
410    strict: bool,
411) -> Result<(super::super::value::ObjRef, String, Value), Value> {
412    let nt = it.take_pending_new_target();
413    if need_new && nt.is_none() {
414        return Err(it.type_error(format!("Constructor Intl.{} requires 'new'", ty)));
415    }
416    let locale = ctor_locale(it, &arg(a, 0))?;
417    let options = get_options_object(it, &arg(a, 1), strict)?;
418    let obj = resolve_intl_this(it, this, ty, nt)?;
419    set_slot(&obj, "_intl_type", ty);
420    Ok((obj, locale, options))
421}
422
423/// 数字の体系(`numberingSystem` オプションとタグの `-u-nu-`)を解決して `(ロケール, 体系)` を返す。
424fn resolve_numbering(it: &mut Interp, options: &Value, tag: &str) -> Result<(String, String), Value> {
425    let nu_opt = opt_str(it, options, "numberingSystem", &[])?.map(|s| s.to_ascii_lowercase());
426    if let Some(n) = &nu_opt {
427        if !super::intl_locale::is_unicode_type_sequence(n) {
428            return Err(it.range_error(format!("Invalid numberingSystem : {}", n)));
429        }
430    }
431    let ext_nu = u_ext_nu(tag).filter(|n| numloc::is_supported_numbering_system(n));
432    let opt_nu = nu_opt.filter(|n| numloc::is_supported_numbering_system(n));
433    let mut locale = strip_extensions(tag);
434    let nu = match (&opt_nu, &ext_nu) {
435        (Some(o), Some(e)) if o == e => {
436            locale = format!("{}-u-nu-{}", locale, o);
437            o.clone()
438        }
439        (Some(o), _) => o.clone(),
440        (None, Some(e)) => {
441            locale = format!("{}-u-nu-{}", locale, e);
442            e.clone()
443        }
444        (None, None) => String::from("latn"),
445    };
446    Ok((locale, nu))
447}
448
449// ===== Intl.getCanonicalLocales =====
450fn canonicalize_locale_list(it: &mut Interp, arg0: &Value) -> Result<Vec<String>, Value> {
451    if matches!(arg0, Value::Undefined) {
452        return Ok(Vec::new());
453    }
454    if matches!(arg0, Value::Null) {
455        return Err(it.type_error("Cannot convert undefined or null to object"));
456    }
457    let mut seen: Vec<String> = Vec::new();
458    let mut push_tag = |tag: String, it: &mut Interp| -> Result<(), Value> {
459        let canon = super::intl_locale::canonicalize_unicode_locale_tag(&tag)
460            .map_err(|m| it.range_error(m))?;
461        if !seen.contains(&canon) {
462            seen.push(canon);
463        }
464        Ok(())
465    };
466
467    if let Some(slot_tag) = super::intl_locale::get_locale_slot(arg0) {
468        push_tag(slot_tag, it)?;
469    } else if arg0.type_of() == "symbol" {
470        // Symbol primitive -> ToObject -> empty array
471    } else if let Value::Str(s) = arg0 {
472        push_tag(String::from(&**s), it)?;
473    } else if let Value::Object(ref o) = arg0 {
474        let len_val = it.get_property(arg0, "length")?;
475        if len_val.type_of() == "symbol" {
476            return Err(it.type_error("Cannot convert a Symbol value to a number"));
477        }
478        let len_prim = if matches!(len_val, Value::Object(_)) {
479            let p = it.to_primitive(len_val, "number")?;
480            if p.type_of() == "symbol" {
481                return Err(it.type_error("Cannot convert a Symbol value to a number"));
482            }
483            p
484        } else {
485            len_val
486        };
487        if matches!(len_prim, Value::BigInt(_)) {
488            return Err(it.type_error("Cannot convert a BigInt value to a number"));
489        }
490        let len_num = len_prim.to_number();
491        let len = if len_num.is_nan() || len_num <= 0.0 {
492            0usize
493        } else {
494            (libm::trunc(len_num) as usize).min(100_000)
495        };
496        for i in 0..len {
497            let key = format!("{}", i);
498            if !it.has_property_chain(o, &key) {
499                continue;
500            }
501            let item = it.get_property(arg0, &key)?;
502            let tag = if let Some(slot_tag) = super::intl_locale::get_locale_slot(&item) {
503                slot_tag
504            } else if item.type_of() == "symbol" {
505                return Err(it.type_error("Language tag must be a string or Locale object"));
506            } else {
507                match &item {
508                    Value::Str(s) => String::from(&**s),
509                    Value::Object(_) => it.to_string_value(item)?,
510                    _ => return Err(it.type_error("Language tag must be a string or Locale object")),
511                }
512            };
513            push_tag(tag, it)?;
514        }
515    }
516    Ok(seen)
517}
518
519pub(crate) fn intl_get_canonical_locales(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
520    let seen = canonicalize_locale_list(it, &arg(a, 0))?;
521    let res_items: Vec<Value> = seen.into_iter().map(|s| Value::Str(Rc::new(s))).collect();
522    Ok(Value::Object(Obj::array(res_items)))
523}
524
525/// `new`を介さない裸呼び出し(`Intl.NumberFormat()`。`Intl`系コンストラクタは
526/// 仕様上どちらの呼び出し形式でも動作可能でなければならない)を正しく扱う。
527/// メンバ呼出(`Intl.NumberFormat(...)`)の`this`は「メンバ式のレシーバ」
528/// (`interp/calls.rs`の`eval_call`のコメントどおり)、つまり`Intl`
529/// 名前空間オブジェクト自身になる。以前は「`this`がオブジェクトなら
530/// そのまま使う」という判定だったため、`new`を省略すると`Intl`オブジェクト
531/// 自身に`_intl_type`/`_locale`を書き込んでしまい(`Intl`名前空間の汚染)、
532/// かつ`Intl`のproto連鎖には`.format`等が無いため常に`undefined`になる
533/// バグだった。正しくは`this`のprotoが既に対象コンストラクタの
534/// `prototype`と一致する場合(`new`経由。`construct_object`が設定済み)
535/// のみそのオブジェクトを再利用し、それ以外(裸呼び出し)は`Intl.<name>.
536/// prototype`へ明示的に繋いだ新規オブジェクトを都度生成する。
537/// 2026-07-18 発見・実装。
538fn proto_chain_includes(obj: &super::super::value::ObjRef, target: &super::super::value::ObjRef) -> bool {
539    let mut cur = obj.borrow().proto.clone();
540    let mut guard = 0usize;
541    while let Some(p) = cur {
542        if Rc::ptr_eq(&p, target) {
543            return true;
544        }
545        guard += 1;
546        if guard > 64 {
547            break;
548        }
549        cur = p.borrow().proto.clone();
550    }
551    false
552}
553
554/// `new` / `Reflect.construct` / `super()` / 裸呼び出し(`Intl.NumberFormat()`)を統一的に扱う。
555/// - `new_target` がある場合は `OrdinaryCreateFromConstructor(newTarget, "%Intl.<ctor>.prototype%")`
556///   に従い `new_target.prototype`(非オブジェクト時は既定プロトタイプ)を解決する。
557/// - `new_target` が無い場合でも `this` のプロトタイプチェーン上に既定プロトタイプがあるなら
558///   サブクラス `super()` 経由のインスタンスとしてそのまま再利用し、裸呼び出し時のみ新規作成する。
559fn resolve_intl_this(
560    it: &mut Interp,
561    this: Value,
562    ctor_name: &str,
563    new_target: Option<Value>,
564) -> Result<super::super::value::ObjRef, Value> {
565    let intl_val = it.global.borrow().vars.get("Intl").cloned();
566    let default_proto = intl_val.and_then(|v| match v {
567        Value::Object(intl) => match intl.borrow().props.get(ctor_name) {
568            Some(Value::Object(ctor)) => match ctor.borrow().props.get("prototype") {
569                Some(Value::Object(p)) => Some(p.clone()),
570                _ => None,
571            },
572            _ => None,
573        },
574        _ => None,
575    });
576    if let Some(nt) = new_target {
577        let nt_proto = if matches!(nt, Value::Object(_)) {
578            match it.get_property(&nt, "prototype")? {
579                Value::Object(p) => Some(p),
580                _ => None,
581            }
582        } else {
583            None
584        };
585        let target_proto = nt_proto.or(default_proto);
586        if let Value::Object(o) = &this {
587            let matches_proto = match (&o.borrow().proto, &target_proto) {
588                (Some(op), Some(tp)) => Rc::ptr_eq(op, tp),
589                _ => false,
590            };
591            if matches_proto {
592                return Ok(o.clone());
593            }
594        }
595        let obj = Obj::plain();
596        if let Some(p) = target_proto {
597            obj.borrow_mut().proto = Some(p);
598        }
599        return Ok(obj);
600    }
601    if let (Value::Object(o), Some(dp)) = (&this, &default_proto) {
602        if proto_chain_includes(o, dp) {
603            return Ok(o.clone());
604        }
605    }
606    let obj = Obj::plain();
607    if let Some(p) = default_proto {
608        obj.borrow_mut().proto = Some(p);
609    }
610    Ok(obj)
611}
612
613// ===== Intl.NumberFormat =====
614use super::super::numloc::{self, DigitOpts, Grouping, NfOptions, Notation, RoundingMode, SignDisplay, Style};
615
616fn opt_obj_get(it: &mut Interp, opts: &Value, key: &str) -> Result<Value, Value> {
617    match opts {
618        Value::Object(_) => it.get_property(opts, key),
619        _ => Ok(Value::Undefined),
620    }
621}
622
623/// 文字列のオプション。許された値以外は RangeError。
624fn opt_str(it: &mut Interp, opts: &Value, key: &str, allowed: &[&str]) -> Result<Option<String>, Value> {
625    match opt_obj_get(it, opts, key)? {
626        Value::Undefined => Ok(None),
627        v => {
628            let s = it.to_string_value(v)?;
629            if !allowed.is_empty() && !allowed.contains(&s.as_str()) {
630                return Err(it.range_error(format!("Value {} out of range for Intl.NumberFormat options property {}", s, key)));
631            }
632            Ok(Some(s))
633        }
634    }
635}
636
637/// 整数のオプション(`min..=max`)。範囲外は RangeError。
638fn opt_num(it: &mut Interp, opts: &Value, key: &str, min: usize, max: usize) -> Result<Option<usize>, Value> {
639    match opt_obj_get(it, opts, key)? {
640        Value::Undefined => Ok(None),
641        v => {
642            let n = v.to_number();
643            if n.is_nan() || n < min as f64 || n > max as f64 {
644                return Err(it.range_error(format!("{} value is out of range.", key)));
645            }
646            Ok(Some(libm::floor(n) as usize))
647        }
648    }
649}
650
651/// ロケールの引数(文字列・配列風オブジェクト・Locale・未指定)から先頭のタグを取る(正規化済み)。
652fn nf_locale(it: &mut Interp, locales: &Value) -> Result<String, Value> {
653    let list = canonicalize_locale_list(it, locales)?;
654    Ok(list.into_iter().next().unwrap_or_else(|| String::from("en-US")))
655}
656
657/// タグの Unicode 拡張(`-u-`)にある `nu` キーの値。
658fn u_ext_nu(tag: &str) -> Option<String> {
659    let mut in_u = false;
660    let mut found = false;
661    let mut val = String::new();
662    for part in tag.split('-') {
663        if part.len() == 1 {
664            if in_u {
665                break;
666            }
667            in_u = part.eq_ignore_ascii_case("u");
668            continue;
669        }
670        if !in_u {
671            continue;
672        }
673        if part.len() == 2 {
674            if found {
675                break;
676            }
677            found = part.eq_ignore_ascii_case("nu");
678            continue;
679        }
680        if found {
681            if !val.is_empty() {
682                val.push('-');
683            }
684            val.push_str(part);
685        }
686    }
687    if found && !val.is_empty() {
688        Some(val.to_ascii_lowercase())
689    } else {
690        None
691    }
692}
693
694/// 拡張(`-u-`・`-x-` など)を除いたタグ。
695fn strip_extensions(tag: &str) -> String {
696    let mut out = String::new();
697    for part in tag.split('-') {
698        if part.len() == 1 {
699            break;
700        }
701        if !out.is_empty() {
702            out.push('-');
703        }
704        out.push_str(part);
705    }
706    out
707}
708
709/// `new Intl.NumberFormat(locales, options)` と `Number.prototype.toLocaleString(locales, options)` の設定の解決。
710pub(crate) fn build_nf_options(it: &mut Interp, locales: &Value, options: &Value) -> Result<NfOptions, Value> {
711    let tag = nf_locale(it, locales)?;
712    if matches!(options, Value::Null) {
713        return Err(it.type_error("Cannot convert undefined or null to object"));
714    }
715    opt_str(it, options, "localeMatcher", &["lookup", "best fit"])?;
716    let nu_opt = opt_str(it, options, "numberingSystem", &[])?.map(|s| s.to_ascii_lowercase());
717    if let Some(n) = &nu_opt {
718        if !super::intl_locale::is_unicode_type_sequence(n) {
719            return Err(it.range_error(format!("Invalid numberingSystem : {}", n)));
720        }
721    }
722    let ext_nu = u_ext_nu(&tag).filter(|n| numloc::is_supported_numbering_system(n));
723    let opt_nu = nu_opt.filter(|n| numloc::is_supported_numbering_system(n));
724    let mut locale = strip_extensions(&tag);
725    let nu = match (&opt_nu, &ext_nu) {
726        (Some(o), Some(e)) if o == e => {
727            locale = format!("{}-u-nu-{}", locale, o);
728            o.clone()
729        }
730        (Some(o), _) => o.clone(),
731        (None, Some(e)) => {
732            locale = format!("{}-u-nu-{}", locale, e);
733            e.clone()
734        }
735        (None, None) => String::from("latn"),
736    };
737    let mut o = NfOptions::new(&locale);
738    o.numbering_system = nu;
739    if let Some(s) = opt_str(it, options, "style", &["decimal", "percent", "currency", "unit"])? {
740        o.style = match s.as_str() {
741            "percent" => Style::Percent,
742            "currency" => Style::Currency,
743            "unit" => Style::Unit,
744            _ => Style::Decimal,
745        };
746    }
747    let currency = opt_str(it, options, "currency", &[])?;
748    if let Some(c) = &currency {
749        if c.len() != 3 || !c.bytes().all(|b| b.is_ascii_alphabetic()) {
750            return Err(it.range_error(format!("Invalid currency code : {}", c)));
751        }
752    }
753    if o.style == Style::Currency && currency.is_none() {
754        return Err(it.type_error("Currency code is required with currency style."));
755    }
756    o.currency = currency.map(|c| c.to_ascii_uppercase()).unwrap_or_default();
757    if let Some(s) = opt_str(it, options, "currencyDisplay", &["code", "symbol", "narrowSymbol", "name"])? {
758        o.currency_display = match s.as_str() {
759            "narrowSymbol" => 1,
760            "code" => 2,
761            "name" => 3,
762            _ => 0,
763        };
764    }
765    if let Some(s) = opt_str(it, options, "currencySign", &["standard", "accounting"])? {
766        o.accounting = s == "accounting";
767    }
768    let unit = opt_str(it, options, "unit", &[])?;
769    if let Some(u) = &unit {
770        if !numloc::is_sanctioned_unit(u) {
771            return Err(it.range_error(format!("Invalid unit argument for Intl.NumberFormat() '{}'", u)));
772        }
773    }
774    if o.style == Style::Unit && unit.is_none() {
775        return Err(it.type_error("Invalid unit argument for Intl.NumberFormat() 'undefined'"));
776    }
777    o.unit = unit.unwrap_or_default();
778    if let Some(s) = opt_str(it, options, "unitDisplay", &["short", "narrow", "long"])? {
779        o.unit_display = match s.as_str() {
780            "narrow" => 1,
781            "long" => 2,
782            _ => 0,
783        };
784    }
785    if let Some(s) = opt_str(it, options, "notation", &["standard", "scientific", "engineering", "compact"])? {
786        o.notation = match s.as_str() {
787            "scientific" => Notation::Scientific,
788            "engineering" => Notation::Engineering,
789            "compact" => Notation::Compact,
790            _ => Notation::Standard,
791        };
792    }
793    let d = DigitOpts {
794        min_int: opt_num(it, options, "minimumIntegerDigits", 1, 21)?,
795        min_frac: opt_num(it, options, "minimumFractionDigits", 0, 100)?,
796        max_frac: opt_num(it, options, "maximumFractionDigits", 0, 100)?,
797        min_sig: opt_num(it, options, "minimumSignificantDigits", 1, 21)?,
798        max_sig: opt_num(it, options, "maximumSignificantDigits", 1, 21)?,
799    };
800    let increment = opt_num(it, options, "roundingIncrement", 1, 5000)?.unwrap_or(1) as u32;
801    if let Some(s) = opt_str(it, options, "roundingMode", &RoundingMode::NAMES)? {
802        if let Some(m) = RoundingMode::from_name(&s) {
803            o.rounding_mode = m;
804        }
805    }
806    let priority = match opt_str(it, options, "roundingPriority", &["auto", "morePrecision", "lessPrecision"])?.as_deref() {
807        Some("morePrecision") => 1,
808        Some("lessPrecision") => 2,
809        _ => 0,
810    };
811    if let Some(s) = opt_str(it, options, "trailingZeroDisplay", &["auto", "stripIfInteger"])? {
812        o.strip_if_integer = s == "stripIfInteger";
813    }
814    if let Err((is_type, m)) = o.resolve_digits_full(d, priority, increment) {
815        return Err(if is_type { it.type_error(m) } else { it.range_error(m) });
816    }
817    if let Some(s) = opt_str(it, options, "compactDisplay", &["short", "long"])? {
818        o.compact_long = s == "long";
819    }
820    o.grouping = if o.notation == Notation::Compact { Grouping::Min2 } else { Grouping::Auto };
821    match opt_obj_get(it, options, "useGrouping")? {
822        Value::Undefined => {}
823        Value::Bool(true) => o.grouping = Grouping::Always,
824        v if !v.truthy() => o.grouping = Grouping::Off,
825        v => {
826            let s = it.to_string_value(v)?;
827            match s.as_str() {
828                "always" => o.grouping = Grouping::Always,
829                "min2" => o.grouping = Grouping::Min2,
830                "auto" => o.grouping = Grouping::Auto,
831                "true" | "false" => {}
832                _ => return Err(it.range_error(format!("Value {} out of range for Intl.NumberFormat options property useGrouping", s))),
833            }
834        }
835    }
836    if let Some(s) = opt_str(it, options, "signDisplay", &["auto", "never", "always", "exceptZero", "negative"])? {
837        o.sign = match s.as_str() {
838            "never" => SignDisplay::Never,
839            "always" => SignDisplay::Always,
840            "exceptZero" => SignDisplay::ExceptZero,
841            "negative" => SignDisplay::Negative,
842            _ => SignDisplay::Auto,
843        };
844    }
845    Ok(o)
846}
847
848fn sv(s: &str) -> Value {
849    Value::Str(Rc::new(String::from(s)))
850}
851
852fn nf_to_obj(o: &NfOptions) -> Value {
853    let r = Obj::plain();
854    {
855        let mut b = r.borrow_mut();
856        b.props.insert("locale".into(), sv(&o.locale));
857        b.props.insert("style".into(), sv(match o.style {
858            Style::Decimal => "decimal",
859            Style::Percent => "percent",
860            Style::Currency => "currency",
861            Style::Unit => "unit",
862        }));
863        b.props.insert("currency".into(), sv(&o.currency));
864        b.props.insert("currencyDisplay".into(), Value::Number(f64::from(o.currency_display)));
865        b.props.insert("unit".into(), sv(&o.unit));
866        b.props.insert("unitDisplay".into(), Value::Number(f64::from(o.unit_display)));
867        b.props.insert("notation".into(), sv(match o.notation {
868            Notation::Standard => "standard",
869            Notation::Compact => "compact",
870            Notation::Scientific => "scientific",
871            Notation::Engineering => "engineering",
872        }));
873        b.props.insert("compactLong".into(), Value::Bool(o.compact_long));
874        b.props.insert("sign".into(), sv(match o.sign {
875            SignDisplay::Auto => "auto",
876            SignDisplay::Never => "never",
877            SignDisplay::Always => "always",
878            SignDisplay::ExceptZero => "exceptZero",
879            SignDisplay::Negative => "negative",
880        }));
881        b.props.insert("grouping".into(), sv(match o.grouping {
882            Grouping::Auto => "auto",
883            Grouping::Always => "always",
884            Grouping::Min2 => "min2",
885            Grouping::Off => "false",
886        }));
887        for (k, v) in [("minInt", o.min_int), ("minFrac", o.min_frac), ("maxFrac", o.max_frac), ("minSig", o.min_sig), ("maxSig", o.max_sig)] {
888            b.props.insert(k.into(), Value::Number(v as f64));
889        }
890        b.props.insert("compactRound".into(), Value::Bool(o.compact_round));
891        b.props.insert("roundingMode".into(), sv(o.rounding_mode.name()));
892        b.props.insert("roundingIncrement".into(), Value::Number(f64::from(o.rounding_increment)));
893        b.props.insert("roundingPriority".into(), Value::Number(f64::from(o.rounding_priority)));
894        b.props.insert("stripIfInteger".into(), Value::Bool(o.strip_if_integer));
895        b.props.insert("numberingSystem".into(), sv(&o.numbering_system));
896        b.props.insert("accounting".into(), Value::Bool(o.accounting));
897    }
898    Value::Object(r)
899}
900
901fn nf_from_obj(v: &Value) -> Option<NfOptions> {
902    let Value::Object(r) = v else { return None };
903    let b = r.borrow();
904    let st = |k: &str| b.props.get(k).map(|x| x.to_js_string()).unwrap_or_default();
905    let num = |k: &str| b.props.get(k).map_or(0, |x| x.to_number() as usize);
906    let mut o = NfOptions::new(&st("locale"));
907    o.style = match st("style").as_str() {
908        "percent" => Style::Percent,
909        "currency" => Style::Currency,
910        "unit" => Style::Unit,
911        _ => Style::Decimal,
912    };
913    o.currency = st("currency");
914    o.currency_display = num("currencyDisplay") as u8;
915    o.unit = st("unit");
916    o.unit_display = num("unitDisplay") as u8;
917    o.notation = match st("notation").as_str() {
918        "compact" => Notation::Compact,
919        "scientific" => Notation::Scientific,
920        "engineering" => Notation::Engineering,
921        _ => Notation::Standard,
922    };
923    o.compact_long = b.props.get("compactLong").is_some_and(Value::truthy);
924    o.sign = match st("sign").as_str() {
925        "never" => SignDisplay::Never,
926        "always" => SignDisplay::Always,
927        "exceptZero" => SignDisplay::ExceptZero,
928        "negative" => SignDisplay::Negative,
929        _ => SignDisplay::Auto,
930    };
931    o.grouping = match st("grouping").as_str() {
932        "always" => Grouping::Always,
933        "min2" => Grouping::Min2,
934        "false" => Grouping::Off,
935        _ => Grouping::Auto,
936    };
937    o.min_int = num("minInt");
938    o.min_frac = num("minFrac");
939    o.max_frac = num("maxFrac");
940    o.min_sig = num("minSig");
941    o.max_sig = num("maxSig");
942    o.compact_round = b.props.get("compactRound").is_some_and(Value::truthy);
943    o.rounding_mode = RoundingMode::from_name(&st("roundingMode")).unwrap_or(RoundingMode::HalfExpand);
944    o.rounding_increment = (num("roundingIncrement") as u32).max(1);
945    o.rounding_priority = num("roundingPriority") as u8;
946    o.strip_if_integer = b.props.get("stripIfInteger").is_some_and(Value::truthy);
947    o.numbering_system = st("numberingSystem");
948    o.accounting = b.props.get("accounting").is_some_and(Value::truthy);
949    Some(o)
950}
951
952pub(crate) fn intl_number_format_ctor(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
953    let nt = it.take_pending_new_target();
954    let opts = build_nf_options(it, &arg(a, 0), &arg(a, 1))?;
955    let obj = resolve_intl_this(it, this, "NumberFormat", nt)?;
956    {
957        let mut b = obj.borrow_mut();
958        b.props.insert("_intl_type".into(), Value::Str(Rc::new("NumberFormat".into())));
959        b.props.insert("_locale".into(), sv(&opts.locale));
960        b.props.insert("_nf".into(), nf_to_obj(&opts));
961    }
962    // `format` は束縛済みの関数(`const f = nf.format; f(1)`・`arr.map(nf.format)` が動く)。
963    let bound = Obj::bound(nv("format", intl_number_format_format), Value::Object(obj.clone()), Vec::new());
964    obj.borrow_mut().props.insert("format".into(), Value::Object(bound));
965    obj.borrow_mut().hide_props(&["_intl_type", "_locale", "_nf", "format"]);
966    Ok(Value::Object(obj))
967}
968
969fn nf_of(this: &Value) -> Option<NfOptions> {
970    match this {
971        Value::Object(o) => nf_from_obj(o.borrow().props.get("_nf")?),
972        _ => None,
973    }
974}
975
976/// 値を数にする(BigInt・文字列も。`Intl.NumberFormat.prototype.format(x)` の ToNumeric)。
977fn nf_value(it: &mut Interp, v: &Value) -> Result<numloc::NumValue, Value> {
978    let prim = match v {
979        Value::Object(_) => it.to_primitive(v.clone(), "number")?,
980        _ => v.clone(),
981    };
982    match &prim {
983        Value::BigInt(b) => Ok(numloc::NumValue::from_int_str(&b.to_radix_string(10))),
984        _ => Ok(numloc::NumValue::from_f64(it.num_of(&prim)?)),
985    }
986}
987
988pub(crate) fn intl_number_format_format(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
989    let Some(o) = nf_of(&this) else {
990        return Err(it.type_error("Method Intl.NumberFormat.prototype.format called on incompatible receiver"));
991    };
992    Ok(Value::Str(Rc::new(numloc::format_value(&nf_value(it, &arg(a, 0))?, &o))))
993}
994
995pub(crate) fn intl_number_format_format_to_parts(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
996    let Some(o) = nf_of(&this) else {
997        return Err(it.type_error("Method Intl.NumberFormat.prototype.formatToParts called on incompatible receiver"));
998    };
999    let parts: Vec<Value> = numloc::format_value_parts(&nf_value(it, &arg(a, 0))?, &o)
1000        .into_iter()
1001        .map(|(ty, val)| {
1002            let p = Obj::plain();
1003            p.borrow_mut().props.insert("type".into(), sv(ty));
1004            p.borrow_mut().props.insert("value".into(), Value::Str(Rc::new(val)));
1005            Value::Object(p)
1006        })
1007        .collect();
1008    Ok(Value::Object(Obj::array(parts)))
1009}
1010
1011pub(crate) fn intl_number_format_resolved_options(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1012    let Some(o) = nf_of(&this) else {
1013        return Err(it.type_error("Method Intl.NumberFormat.prototype.resolvedOptions called on incompatible receiver"));
1014    };
1015    let res = Obj::plain();
1016    {
1017        let mut b = res.borrow_mut();
1018        let num = |n: usize| Value::Number(n as f64);
1019        b.props.insert("locale".into(), sv(&o.locale));
1020        b.props.insert("numberingSystem".into(), sv(&o.numbering_system));
1021        b.props.insert("style".into(), sv(match o.style {
1022            Style::Decimal => "decimal",
1023            Style::Percent => "percent",
1024            Style::Currency => "currency",
1025            Style::Unit => "unit",
1026        }));
1027        if o.style == Style::Currency {
1028            b.props.insert("currency".into(), sv(&o.currency));
1029            b.props.insert("currencyDisplay".into(), sv(["symbol", "narrowSymbol", "code", "name"].get(usize::from(o.currency_display)).copied().unwrap_or("symbol")));
1030            b.props.insert("currencySign".into(), sv(if o.accounting { "accounting" } else { "standard" }));
1031        }
1032        if o.style == Style::Unit {
1033            b.props.insert("unit".into(), sv(&o.unit));
1034            b.props.insert("unitDisplay".into(), sv(["short", "narrow", "long"].get(usize::from(o.unit_display)).copied().unwrap_or("short")));
1035        }
1036        b.props.insert("minimumIntegerDigits".into(), num(o.min_int));
1037        let both = o.rounding_priority != 0 || o.compact_round;
1038        if both || o.max_sig == 0 {
1039            b.props.insert("minimumFractionDigits".into(), num(o.min_frac));
1040            b.props.insert("maximumFractionDigits".into(), num(o.max_frac));
1041        }
1042        if o.compact_round {
1043            b.props.insert("minimumSignificantDigits".into(), num(1));
1044            b.props.insert("maximumSignificantDigits".into(), num(2));
1045        } else if o.max_sig > 0 {
1046            b.props.insert("minimumSignificantDigits".into(), num(o.min_sig));
1047            b.props.insert("maximumSignificantDigits".into(), num(o.max_sig));
1048        }
1049        b.props.insert("useGrouping".into(), match o.grouping {
1050            Grouping::Off => Value::Bool(false),
1051            Grouping::Always => sv("always"),
1052            Grouping::Min2 => sv("min2"),
1053            Grouping::Auto => sv("auto"),
1054        });
1055        b.props.insert("notation".into(), sv(match o.notation {
1056            Notation::Standard => "standard",
1057            Notation::Compact => "compact",
1058            Notation::Scientific => "scientific",
1059            Notation::Engineering => "engineering",
1060        }));
1061        if o.notation == Notation::Compact {
1062            b.props.insert("compactDisplay".into(), sv(if o.compact_long { "long" } else { "short" }));
1063        }
1064        b.props.insert("signDisplay".into(), sv(match o.sign {
1065            SignDisplay::Auto => "auto",
1066            SignDisplay::Never => "never",
1067            SignDisplay::Always => "always",
1068            SignDisplay::ExceptZero => "exceptZero",
1069            SignDisplay::Negative => "negative",
1070        }));
1071        b.props.insert("roundingIncrement".into(), num(o.rounding_increment as usize));
1072        b.props.insert("roundingMode".into(), sv(o.rounding_mode.name()));
1073        b.props.insert("roundingPriority".into(), sv(match (o.compact_round, o.rounding_priority) {
1074            (true, _) | (_, 1) => "morePrecision",
1075            (_, 2) => "lessPrecision",
1076            _ => "auto",
1077        }));
1078        b.props.insert("trailingZeroDisplay".into(), sv(if o.strip_if_integer { "stripIfInteger" } else { "auto" }));
1079    }
1080    Ok(Value::Object(res))
1081}
1082
1083// ===== Intl.DateTimeFormat =====
1084pub(crate) fn intl_datetime_format_ctor(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1085    let (obj, locale, _options) = intl_ctor_common(it, this, a, "DateTimeFormat", false, false)?;
1086    set_slot(&obj, "_locale", &locale);
1087    Ok(Value::Object(obj))
1088}
1089
1090pub(crate) fn intl_datetime_format_format(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1091    let val = arg(a, 0);
1092    let _ = this;
1093    let formatted = val.to_js_string();
1094    Ok(Value::Str(Rc::new(formatted)))
1095}
1096
1097pub(crate) fn intl_datetime_format_format_to_parts(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1098    require_brand(it, &this, "DateTimeFormat", "formatToParts")?;
1099    let val = arg(a, 0);
1100    let formatted = val.to_js_string();
1101    let parts = vec![
1102        {
1103            let p = Obj::plain();
1104            p.borrow_mut().props.insert("type".into(), Value::Str(Rc::new("literal".into())));
1105            p.borrow_mut().props.insert("value".into(), Value::Str(Rc::new(formatted)));
1106            Value::Object(p)
1107        }
1108    ];
1109    Ok(Value::Object(Obj::array(parts)))
1110}
1111
1112pub(crate) fn intl_datetime_format_resolved_options(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1113    require_brand(it, &this, "DateTimeFormat", "resolvedOptions")?;
1114    let locale = slot(&this, "_locale").unwrap_or_else(|| String::from("en-US"));
1115    let res = Obj::plain();
1116    res.borrow_mut().props.insert("locale".into(), Value::Str(Rc::new(locale)));
1117    res.borrow_mut().props.insert("calendar".into(), Value::Str(Rc::new("gregory".into())));
1118    res.borrow_mut().props.insert("timeZone".into(), Value::Str(Rc::new("UTC".into())));
1119    // 既定の日付の形(年・月・日は numeric)。自前で持つので `Object.prototype` に足された名前は見えない。
1120    for k in ["year", "month", "day"] {
1121        res.borrow_mut().props.insert(k.into(), Value::Str(Rc::new("numeric".into())));
1122    }
1123    Ok(Value::Object(res))
1124}
1125
1126// ===== Intl.Collator =====
1127pub(crate) fn intl_collator_ctor(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1128    let (obj, locale, _options) = intl_ctor_common(it, this, a, "Collator", false, false)?;
1129    set_slot(&obj, "_locale", &locale);
1130    let bound = Obj::bound(nv("compare", intl_collator_compare), Value::Object(obj.clone()), Vec::new());
1131    obj.borrow_mut().props.insert("compare".into(), Value::Object(bound));
1132    obj.borrow_mut().hide_props(&["compare"]);
1133    Ok(Value::Object(obj))
1134}
1135
1136pub(crate) fn intl_collator_compare(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1137    let s1 = it.to_string_value(arg(a, 0))?;
1138    let s2 = it.to_string_value(arg(a, 1))?;
1139    let phonebook = slot(&this, "_locale").is_some_and(|l| l.contains("-u-co-phonebk"));
1140    let cmp = crate::os_lib::ecma::collate::locale_compare_with_options(&s1, &s2, phonebook) as i32;
1141    Ok(Value::Number(cmp as f64))
1142}
1143
1144pub(crate) fn intl_collator_resolved_options(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1145    require_brand(it, &this, "Collator", "resolvedOptions")?;
1146    let locale = slot(&this, "_locale").unwrap_or_else(|| String::from("en-US"));
1147    let res = Obj::plain();
1148    res.borrow_mut().props.insert("locale".into(), Value::Str(Rc::new(locale)));
1149    res.borrow_mut().props.insert("usage".into(), Value::Str(Rc::new("sort".into())));
1150    res.borrow_mut().props.insert("sensitivity".into(), Value::Str(Rc::new("variant".into())));
1151    Ok(Value::Object(res))
1152}
1153
1154// ===== Intl.PluralRules =====
1155pub(crate) fn intl_plural_rules_ctor(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1156    let (obj, locale, _options) = intl_ctor_common(it, this, a, "PluralRules", false, false)?;
1157    set_slot(&obj, "_locale", &locale);
1158    Ok(Value::Object(obj))
1159}
1160
1161pub(crate) fn intl_plural_rules_select(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1162    require_brand(it, &this, "PluralRules", "select")?;
1163    let n = it.num_of(&arg(a, 0))?;
1164    let category = if n == 1.0 { "one" } else { "other" };
1165    Ok(Value::Str(Rc::new(category.into())))
1166}
1167
1168pub(crate) fn intl_plural_rules_resolved_options(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1169    require_brand(it, &this, "PluralRules", "resolvedOptions")?;
1170    let locale = slot(&this, "_locale").unwrap_or_else(|| String::from("en-US"));
1171    let res = Obj::plain();
1172    res.borrow_mut().props.insert("locale".into(), Value::Str(Rc::new(locale)));
1173    res.borrow_mut().props.insert("type".into(), Value::Str(Rc::new("cardinal".into())));
1174    Ok(Value::Object(res))
1175}
1176
1177// ===== Intl.RelativeTimeFormat =====
1178pub(crate) fn intl_relative_time_format_ctor(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1179    let (obj, locale, _options) = intl_ctor_common(it, this, a, "RelativeTimeFormat", false, false)?;
1180    set_slot(&obj, "_locale", &locale);
1181    Ok(Value::Object(obj))
1182}
1183
1184pub(crate) fn intl_relative_time_format_format(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1185    require_brand(it, &this, "RelativeTimeFormat", "format")?;
1186    let value = it.num_of(&arg(a, 0))?;
1187    let unit = it.to_string_value(arg(a, 1))?;
1188    let formatted = if value < 0.0 {
1189        format!("{} {}s ago", -value, unit)
1190    } else {
1191        format!("in {} {}s", value, unit)
1192    };
1193    Ok(Value::Str(Rc::new(formatted)))
1194}
1195
1196pub(crate) fn intl_relative_time_format_format_to_parts(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1197    let res = intl_relative_time_format_format(it, this, a)?;
1198    let parts = vec![
1199        {
1200            let p = Obj::plain();
1201            p.borrow_mut().props.insert("type".into(), Value::Str(Rc::new("literal".into())));
1202            p.borrow_mut().props.insert("value".into(), res);
1203            Value::Object(p)
1204        }
1205    ];
1206    Ok(Value::Object(Obj::array(parts)))
1207}
1208
1209pub(crate) fn intl_relative_time_format_resolved_options(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1210    require_brand(it, &this, "RelativeTimeFormat", "resolvedOptions")?;
1211    let locale = slot(&this, "_locale").unwrap_or_else(|| String::from("en-US"));
1212    let res = Obj::plain();
1213    res.borrow_mut().props.insert("locale".into(), Value::Str(Rc::new(locale)));
1214    res.borrow_mut().props.insert("style".into(), Value::Str(Rc::new("long".into())));
1215    res.borrow_mut().props.insert("numeric".into(), Value::Str(Rc::new("always".into())));
1216    Ok(Value::Object(res))
1217}
1218
1219// ===== Intl.Segmenter =====
1220pub(crate) fn intl_segmenter_ctor(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1221    let (obj, locale, _options) = intl_ctor_common(it, this, a, "Segmenter", false, true)?;
1222    set_slot(&obj, "_locale", &locale);
1223    Ok(Value::Object(obj))
1224}
1225
1226pub(crate) fn intl_segmenter_segment(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1227    require_brand(it, &this, "Segmenter", "segment")?;
1228    let str_val = it.to_string_value(arg(a, 0))?;
1229    let segments: Vec<Value> = str_val
1230        .chars()
1231        .enumerate()
1232        .map(|(idx, ch)| {
1233            let seg = Obj::plain();
1234            seg.borrow_mut().props.insert("segment".into(), Value::Str(Rc::new(ch.to_string())));
1235            seg.borrow_mut().props.insert("index".into(), Value::Number(idx as f64));
1236            seg.borrow_mut().props.insert("input".into(), Value::Str(Rc::new(str_val.clone())));
1237            Value::Object(seg)
1238        })
1239        .collect();
1240    let result = Obj::plain();
1241    result.borrow_mut().props.insert("containing".into(), nv("containing", |_it, _this, _a| Ok(Value::Undefined)));
1242    result.borrow_mut().props.insert("_segments".into(), Value::Object(Obj::array(segments)));
1243    result.borrow_mut().props.insert(
1244        "Symbol(Symbol.iterator)".into(),
1245        nv("[Symbol.iterator]", |_it, this, _a| {
1246            let items = if let Value::Object(o) = &this {
1247                match o.borrow().props.get("_segments").cloned() {
1248                    Some(Value::Object(arr)) => match &arr.borrow().kind {
1249                        ObjKind::Array(v) => v.clone(),
1250                        _ => Vec::new(),
1251                    },
1252                    _ => Vec::new(),
1253                }
1254            } else {
1255                Vec::new()
1256            };
1257            Ok(Value::Object(super::make_iterator(items)))
1258        }),
1259    );
1260    Ok(Value::Object(result))
1261}
1262
1263pub(crate) fn intl_segmenter_resolved_options(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1264    require_brand(it, &this, "Segmenter", "resolvedOptions")?;
1265    let locale = slot(&this, "_locale").unwrap_or_else(|| String::from("en-US"));
1266    let res = Obj::plain();
1267    res.borrow_mut().props.insert("locale".into(), Value::Str(Rc::new(locale)));
1268    res.borrow_mut().props.insert("granularity".into(), Value::Str(Rc::new("grapheme".into())));
1269    Ok(Value::Object(res))
1270}
1271
1272// ===== Intl.ListFormat =====
1273pub(crate) fn intl_list_format_ctor(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1274    let (obj, locale, _options) = intl_ctor_common(it, this, a, "ListFormat", false, true)?;
1275    set_slot(&obj, "_locale", &locale);
1276    Ok(Value::Object(obj))
1277}
1278
1279pub(crate) fn intl_list_format_format(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1280    require_brand(it, &this, "ListFormat", "format")?;
1281    let arg0 = arg(a, 0);
1282    let mut items = Vec::new();
1283    if let Value::Object(o) = &arg0 {
1284        if let ObjKind::Array(list) = &o.borrow().kind {
1285            for item in list {
1286                items.push(item.to_js_string());
1287            }
1288        }
1289    }
1290    let formatted = items.join(", ");
1291    Ok(Value::Str(Rc::new(formatted)))
1292}
1293
1294pub(crate) fn intl_list_format_format_to_parts(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1295    let res = intl_list_format_format(it, this, a)?;
1296    let parts = vec![
1297        {
1298            let p = Obj::plain();
1299            p.borrow_mut().props.insert("type".into(), Value::Str(Rc::new("element".into())));
1300            p.borrow_mut().props.insert("value".into(), res);
1301            Value::Object(p)
1302        }
1303    ];
1304    Ok(Value::Object(Obj::array(parts)))
1305}
1306
1307pub(crate) fn intl_list_format_resolved_options(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1308    require_brand(it, &this, "ListFormat", "resolvedOptions")?;
1309    let locale = slot(&this, "_locale").unwrap_or_else(|| String::from("en-US"));
1310    let res = Obj::plain();
1311    res.borrow_mut().props.insert("locale".into(), Value::Str(Rc::new(locale)));
1312    res.borrow_mut().props.insert("type".into(), Value::Str(Rc::new("conjunction".into())));
1313    res.borrow_mut().props.insert("style".into(), Value::Str(Rc::new("long".into())));
1314    Ok(Value::Object(res))
1315}
1316
1317// ===== Intl.DisplayNames =====
1318pub(crate) fn intl_display_names_ctor(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1319    let (obj, locale, _options) = intl_ctor_common(it, this, a, "DisplayNames", false, true)?;
1320    set_slot(&obj, "_locale", &locale);
1321    Ok(Value::Object(obj))
1322}
1323
1324pub(crate) fn intl_display_names_of(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1325    require_brand(it, &this, "DisplayNames", "of")?;
1326    let code = it.to_string_value(arg(a, 0))?;
1327    Ok(Value::Str(Rc::new(code)))
1328}
1329
1330pub(crate) fn intl_display_names_resolved_options(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1331    require_brand(it, &this, "DisplayNames", "resolvedOptions")?;
1332    let locale = slot(&this, "_locale").unwrap_or_else(|| String::from("en-US"));
1333    let res = Obj::plain();
1334    res.borrow_mut().props.insert("locale".into(), Value::Str(Rc::new(locale)));
1335    res.borrow_mut().props.insert("style".into(), Value::Str(Rc::new("long".into())));
1336    res.borrow_mut().props.insert("fallback".into(), Value::Str(Rc::new("code".into())));
1337    Ok(Value::Object(res))
1338}
1339
1340// ===== Intl.DurationFormat =====
1341pub(crate) fn intl_duration_format_ctor(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1342    let (obj, locale, options) = intl_ctor_common(it, this, a, "DurationFormat", false, true)?;
1343    let style = opt_str(it, &options, "style", &["long", "short", "narrow", "digital"])?
1344        .unwrap_or_else(|| String::from("short"));
1345    set_slot(&obj, "_locale", &locale);
1346    set_slot(&obj, "_style", &style);
1347    Ok(Value::Object(obj))
1348}
1349
1350pub(crate) fn intl_duration_format_format(_it: &mut Interp, _this: Value, a: &[Value]) -> Result<Value, Value> {
1351    let dur_obj = arg(a, 0);
1352    let units = [
1353        ("years", "year", "years"),
1354        ("months", "month", "months"),
1355        ("weeks", "week", "weeks"),
1356        ("days", "day", "days"),
1357        ("hours", "hour", "hours"),
1358        ("minutes", "minute", "minutes"),
1359        ("seconds", "second", "seconds"),
1360        ("milliseconds", "millisecond", "milliseconds"),
1361        ("microseconds", "microsecond", "microseconds"),
1362        ("nanoseconds", "nanosecond", "nanoseconds"),
1363    ];
1364
1365    let mut parts = Vec::new();
1366    if let Value::Object(o) = &dur_obj {
1367        let props = &o.borrow().props;
1368        for &(key, singular, plural) in &units {
1369            if let Some(val) = props.get(key) {
1370                let num = val.to_number();
1371                if num.is_finite() && num != 0.0 {
1372                    let unit_str = if num.abs() == 1.0 { singular } else { plural };
1373                    parts.push(format!("{} {}", num, unit_str));
1374                }
1375            }
1376        }
1377    }
1378    let formatted = if parts.is_empty() {
1379        String::from("0 seconds")
1380    } else {
1381        parts.join(", ")
1382    };
1383    Ok(Value::Str(Rc::new(formatted)))
1384}
1385
1386pub(crate) fn intl_duration_format_format_to_parts(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1387    let formatted = intl_duration_format_format(it, this, a)?;
1388    let p = Obj::plain();
1389    p.borrow_mut().props.insert("type".into(), Value::Str(Rc::new("integer".into())));
1390    p.borrow_mut().props.insert("value".into(), formatted);
1391    Ok(Value::Object(Obj::array(vec![Value::Object(p)])))
1392}
1393
1394pub(crate) fn intl_duration_format_resolved_options(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1395    let (locale, style) = if let Value::Object(o) = &this {
1396        let l = o.borrow().props.get("_locale").cloned().unwrap_or(Value::Str(Rc::new("en-US".into()))).to_js_string();
1397        let s = o.borrow().props.get("_style").cloned().unwrap_or(Value::Str(Rc::new("long".into()))).to_js_string();
1398        (l, s)
1399    } else {
1400        (String::from("en-US"), String::from("long"))
1401    };
1402    let res = Obj::plain();
1403    res.borrow_mut().props.insert("locale".into(), Value::Str(Rc::new(locale)));
1404    res.borrow_mut().props.insert("style".into(), Value::Str(Rc::new(style)));
1405    Ok(Value::Object(res))
1406}