NumberFormatConstructor.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. using Jint.Native.Function;
  2. using Jint.Native.Object;
  3. using Jint.Runtime;
  4. using Jint.Runtime.Descriptors;
  5. namespace Jint.Native.Intl;
  6. /// <summary>
  7. /// https://tc39.es/ecma402/#sec-intl-numberformat-constructor
  8. /// </summary>
  9. internal sealed class NumberFormatConstructor : Constructor
  10. {
  11. private static readonly JsString _functionName = new("NumberFormat");
  12. public NumberFormatConstructor(
  13. Engine engine,
  14. Realm realm,
  15. FunctionPrototype functionPrototype,
  16. ObjectPrototype objectPrototype) : base(engine, realm, _functionName)
  17. {
  18. _prototype = functionPrototype;
  19. PrototypeObject = new NumberFormatPrototype(engine, realm, this, objectPrototype);
  20. _length = new PropertyDescriptor(JsNumber.PositiveZero, PropertyFlag.Configurable);
  21. _prototypeDescriptor = new PropertyDescriptor(PrototypeObject, PropertyFlag.AllForbidden);
  22. }
  23. public NumberFormatPrototype PrototypeObject { get; }
  24. public object LocaleData { get; private set; } = null!;
  25. public object AvailableLocales { get; private set; } = null!;
  26. public object RelevantExtensionKeys { get; private set; } = null!;
  27. protected override void Initialize()
  28. {
  29. LocaleData = new object();
  30. AvailableLocales = new object();
  31. RelevantExtensionKeys = new object();
  32. }
  33. /// <summary>
  34. /// https://tc39.es/ecma402/#sec-intl.numberformat
  35. /// </summary>
  36. public override ObjectInstance Construct(JsValue[] arguments, JsValue newTarget)
  37. {
  38. var locales = arguments.At(0);
  39. var options = arguments.At(1);
  40. if (newTarget.IsUndefined())
  41. {
  42. newTarget = this;
  43. }
  44. var numberFormat = OrdinaryCreateFromConstructor<JsObject, object>(
  45. newTarget,
  46. static intrinsics => intrinsics.NumberFormat.PrototypeObject,
  47. static (engine, _, _) => new JsObject(engine));
  48. InitializeNumberFormat(numberFormat, locales, options);
  49. return numberFormat;
  50. }
  51. /// <summary>
  52. /// https://tc39.es/ecma402/#sec-initializenumberformat
  53. /// </summary>
  54. private JsObject InitializeNumberFormat(JsObject numberFormat, JsValue locales, JsValue opts)
  55. {
  56. var requestedLocales = CanonicalizeLocaleList(locales);
  57. var options = CoerceOptionsToObject(opts);
  58. var opt = new JsObject(_engine);
  59. var matcher = GetOption(options, "localeMatcher", OptionType.String, new JsValue[] { "lookup", "best fit" }, "best fit");
  60. opt["localeMatcher"] = matcher;
  61. var numberingSystem = GetOption(options, "numberingSystem", OptionType.String, System.Array.Empty<JsValue>(), Undefined);
  62. if (!numberingSystem.IsUndefined())
  63. {
  64. // If numberingSystem does not match the Unicode Locale Identifier type nonterminal, throw a RangeError exception.
  65. }
  66. opt["nu"] = numberingSystem;
  67. var localeData = LocaleData;
  68. var r = ResolveLocale(_engine.Realm.Intrinsics.NumberFormat.AvailableLocales, requestedLocales, opt, _engine.Realm.Intrinsics.NumberFormat.RelevantExtensionKeys, localeData);
  69. numberFormat["Locale"] = r["locale"];
  70. numberFormat["DataLocale"] = r["dataLocale"];
  71. numberFormat["NumberingSystem"] = r["nu"];
  72. SetNumberFormatUnitOptions(numberFormat, options);
  73. int mnfdDefault;
  74. int mxfdDefault;
  75. var style = numberFormat["Style"];
  76. if (style == "currency")
  77. {
  78. var currency = numberFormat["Currency"];
  79. var cDigits = CurrencyDigits(currency);
  80. mnfdDefault = cDigits;
  81. mxfdDefault = cDigits;
  82. }
  83. else
  84. {
  85. mnfdDefault = 0;
  86. mxfdDefault = style == "percent" ? 0 : 3;
  87. }
  88. var notation = GetOption(options, "notation", OptionType.String, new JsValue[] { "standard", "scientific", "engineering", "compact" }, "standard");
  89. numberFormat["Notation"] = notation;
  90. SetNumberFormatDigitOptions(numberFormat, options, mnfdDefault, mxfdDefault, notation.ToString());
  91. var compactDisplay = GetOption(options, "compactDisplay", OptionType.String, new JsValue[] { "short", "long" }, "short");
  92. if (notation == "compact")
  93. {
  94. numberFormat["CompactDisplay"] = compactDisplay;
  95. }
  96. var useGrouping = GetOption(options, "useGrouping", OptionType.Boolean, System.Array.Empty<JsValue>(), JsBoolean.True);
  97. numberFormat["UseGrouping"] = useGrouping;
  98. var signDisplay = GetOption(options, "signDisplay", OptionType.String, new JsValue[] { "auto", "never", "always", "exceptZero" }, "auto");
  99. numberFormat["SignDisplay"] = signDisplay;
  100. return numberFormat;
  101. }
  102. /// <summary>
  103. /// https://tc39.es/ecma402/#sec-resolvelocale
  104. /// </summary>
  105. private JsObject ResolveLocale(object availableLocales, JsArray requestedLocales, JsObject options, object relevantExtensionKeys, object localeData)
  106. {
  107. // TODO
  108. var result = new JsObject(_engine);
  109. return result;
  110. }
  111. /// <summary>
  112. /// https://tc39.es/ecma402/#sec-setnfdigitoptions
  113. /// </summary>
  114. private static void SetNumberFormatDigitOptions(JsObject numberFormat, ObjectInstance options, int mnfdDefault, int mxfdDefault, string notation)
  115. {
  116. // TODO
  117. }
  118. /// <summary>
  119. /// https://tc39.es/ecma402/#sec-currencydigits
  120. /// </summary>
  121. private static int CurrencyDigits(JsValue currency)
  122. {
  123. // TODO
  124. return 2;
  125. }
  126. /// <summary>
  127. /// https://tc39.es/ecma402/#sec-setnumberformatunitoptions
  128. /// </summary>
  129. private void SetNumberFormatUnitOptions(JsObject intlObj, JsValue options)
  130. {
  131. var style = GetOption(options, "style", OptionType.String, new JsValue[] { "decimal", "percent", "currency", "unit" }, "decimal");
  132. intlObj["Style"] = style;
  133. var currency = GetOption(options, "currency", OptionType.String, System.Array.Empty<JsValue>(), Undefined);
  134. if (currency.IsUndefined())
  135. {
  136. if (style == "currency")
  137. {
  138. ExceptionHelper.ThrowTypeError(_realm, "No currency found when style currency requested");
  139. }
  140. }
  141. else if (!IsWellFormedCurrencyCode(currency))
  142. {
  143. ExceptionHelper.ThrowRangeError(_realm, "Invalid currency code");
  144. }
  145. var currencyDisplay = GetOption(options, "currencyDisplay", OptionType.String, new JsValue[] { "code", "symbol", "narrowSymbol", "name" }, "symbol");
  146. var currencySign = GetOption(options, "currencySign", OptionType.String, new JsValue[] { "standard", "accounting" }, "standard");
  147. var unit = GetOption(options, "unit", OptionType.String, System.Array.Empty<JsValue>(), Undefined);
  148. if (unit.IsUndefined())
  149. {
  150. if (style == "unit")
  151. {
  152. ExceptionHelper.ThrowTypeError(_realm, "No unit found when style unit requested");
  153. }
  154. }
  155. else if (!IsWellFormedUnitIdentifier(unit))
  156. {
  157. ExceptionHelper.ThrowRangeError(_realm, "Invalid unit");
  158. }
  159. var unitDisplay = GetOption(options, "unitDisplay", OptionType.String, new JsValue[] { "short", "narrow", "long" }, "short");
  160. if (style == "currency")
  161. {
  162. intlObj["Currency"] = currency.ToString().ToUpperInvariant();
  163. intlObj["CurrencyDisplay"] = currencyDisplay;
  164. intlObj["CurrencySign"] = currencySign;
  165. }
  166. if (style == "unit")
  167. {
  168. intlObj["Unit"] = unit;
  169. intlObj["UnitDisplay"] = unitDisplay;
  170. }
  171. }
  172. /// <summary>
  173. /// https://tc39.es/ecma402/#sec-iswellformedunitidentifier
  174. /// </summary>
  175. private static bool IsWellFormedUnitIdentifier(JsValue unitIdentifier)
  176. {
  177. var value = unitIdentifier.ToString();
  178. if (IsSanctionedSingleUnitIdentifier(value))
  179. {
  180. return true;
  181. }
  182. var i = value.IndexOf("-per-", StringComparison.Ordinal);
  183. if (i == -1 || value.IndexOf("-per-", i + 1, StringComparison.Ordinal) != -1)
  184. {
  185. return false;
  186. }
  187. var numerator = value.Substring(0, i);
  188. var denominator = value.Substring(i + 5);
  189. if (IsSanctionedSingleUnitIdentifier(numerator) && IsSanctionedSingleUnitIdentifier(denominator))
  190. {
  191. return true;
  192. }
  193. return false;
  194. }
  195. private static readonly HashSet<string> _sanctionedSingleUnitIdentifiers = new(StringComparer.Ordinal)
  196. {
  197. "acre",
  198. "bit",
  199. "byte",
  200. "celsius",
  201. "centimeter",
  202. "day",
  203. "degree",
  204. "fahrenheit",
  205. "fluid-ounce",
  206. "foot",
  207. "gallon",
  208. "gigabit",
  209. "gigabyte",
  210. "gram",
  211. "hectare",
  212. "hour",
  213. "inch",
  214. "kilobit",
  215. "kilobyte",
  216. "kilogram",
  217. "kilometer",
  218. "liter",
  219. "megabit",
  220. "megabyte",
  221. "meter",
  222. "microsecond",
  223. "mile",
  224. "mile-scandinavian",
  225. "milliliter",
  226. "millimeter",
  227. "millisecond",
  228. "minute",
  229. "month",
  230. "nanosecond",
  231. "ounce",
  232. "percent",
  233. "petabyte",
  234. "pound",
  235. "second",
  236. "stone",
  237. "terabit",
  238. "terabyte",
  239. "week",
  240. "yard",
  241. "year",
  242. };
  243. /// <summary>
  244. /// https://tc39.es/ecma402/#sec-issanctionedsingleunitidentifier
  245. /// </summary>
  246. private static bool IsSanctionedSingleUnitIdentifier(string unitIdentifier) => _sanctionedSingleUnitIdentifiers.Contains(unitIdentifier);
  247. /// <summary>
  248. /// https://tc39.es/ecma402/#sec-iswellformedcurrencycode
  249. /// </summary>
  250. private static bool IsWellFormedCurrencyCode(JsValue currency)
  251. {
  252. var value = currency.ToString();
  253. return value.Length == 3 && char.IsLetter(value[0]) && char.IsLetter(value[1]) && char.IsLetter(value[2]);
  254. }
  255. /// <summary>
  256. /// https://tc39.es/ecma402/#sec-coerceoptionstoobject
  257. /// </summary>
  258. private ObjectInstance CoerceOptionsToObject(JsValue options)
  259. {
  260. if (options.IsUndefined())
  261. {
  262. return OrdinaryObjectCreate(_engine, null);
  263. }
  264. return TypeConverter.ToObject(_realm, options);
  265. }
  266. /// <summary>
  267. /// https://tc39.es/ecma402/#sec-canonicalizelocalelist
  268. /// </summary>
  269. private JsArray CanonicalizeLocaleList(JsValue locales)
  270. {
  271. return new JsArray(_engine);
  272. // TODO
  273. }
  274. private enum OptionType
  275. {
  276. Boolean,
  277. Number,
  278. String
  279. }
  280. /// <summary>
  281. /// https://tc39.es/ecma402/#sec-getoption
  282. /// </summary>
  283. private JsValue GetOption<T>(JsValue options, string property, OptionType type, T[] values, T defaultValue) where T : JsValue
  284. {
  285. var value = options.Get(property);
  286. if (value.IsUndefined())
  287. {
  288. if (defaultValue == "required")
  289. {
  290. ExceptionHelper.ThrowRangeError(_realm, "Required value missing");
  291. }
  292. return defaultValue;
  293. }
  294. switch (type)
  295. {
  296. case OptionType.Boolean:
  297. value = TypeConverter.ToBoolean(value);
  298. break;
  299. case OptionType.Number:
  300. {
  301. var number = TypeConverter.ToNumber(value);
  302. if (double.IsNaN(number))
  303. {
  304. ExceptionHelper.ThrowRangeError(_realm, "Invalid number value");
  305. }
  306. value = number;
  307. break;
  308. }
  309. case OptionType.String:
  310. value = TypeConverter.ToString(value);
  311. break;
  312. default:
  313. ExceptionHelper.ThrowArgumentOutOfRangeException(nameof(type), "Unknown type");
  314. break;
  315. }
  316. if (values.Length > 0 && System.Array.IndexOf(values, value) == -1)
  317. {
  318. ExceptionHelper.ThrowRangeError(_realm, "Value not part of list");
  319. }
  320. return value;
  321. }
  322. }