IntlEngineInterfaceExtensionObject.cpp 143 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "RuntimeLibraryPch.h"
  6. #include "EngineInterfaceObject.h"
  7. #include "IntlEngineInterfaceExtensionObject.h"
  8. #include "Types/DeferredTypeHandler.h"
  9. #include "Base/WindowsGlobalizationAdapter.h"
  10. #ifdef ENABLE_INTL_OBJECT
  11. #include "ByteCode/ByteCodeSerializer.h"
  12. #include "errstr.h"
  13. #include "ByteCode/ByteCodeDumper.h"
  14. #include "Codex/Utf8Helper.h"
  15. #ifdef INTL_WINGLOB
  16. using namespace Windows::Globalization;
  17. #endif
  18. #ifdef INTL_ICU
  19. #include <CommonPal.h>
  20. #include "PlatformAgnostic/ChakraICU.h"
  21. using namespace PlatformAgnostic::ICUHelpers;
  22. #if defined(DBG) || defined(ENABLE_DEBUG_CONFIG_OPTIONS)
  23. #define INTL_TRACE(fmt, ...) Output::Trace(Js::IntlPhase, _u("%S(): " fmt "\n"), __func__, __VA_ARGS__)
  24. #else
  25. #define INTL_TRACE(fmt, ...)
  26. #endif
  27. #define ICU_ASSERT(e, expr) \
  28. do \
  29. { \
  30. if (e == U_MEMORY_ALLOCATION_ERROR) \
  31. { \
  32. Js::Throw::OutOfMemory(); \
  33. } \
  34. else if (ICU_FAILURE(e)) \
  35. { \
  36. AssertOrFailFastMsg(false, ICU_ERRORMESSAGE(e)); \
  37. } \
  38. else if (!(expr)) \
  39. { \
  40. AssertOrFailFast(expr); \
  41. } \
  42. } while (false)
  43. #endif // INTL_ICU
  44. // NOTE(jahorto): Keep these enums in sync with those by the same name in Intl.js
  45. // These enums are used by both WinGlob- and ICU-backed Intl
  46. enum class NumberFormatStyle
  47. {
  48. Decimal, // Intl.NumberFormat(locale, { style: "decimal" }); // aka in our code as "number"
  49. Percent, // Intl.NumberFormat(locale, { style: "percent" });
  50. Currency, // Intl.NumberFormat(locale, { style: "currency", ... });
  51. Max,
  52. Default = Decimal,
  53. };
  54. enum class NumberFormatCurrencyDisplay
  55. {
  56. Symbol, // Intl.NumberFormat(locale, { style: "currency", currencyDisplay: "symbol" }); // e.g. "$" or "US$" depeding on locale
  57. Code, // Intl.NumberFormat(locale, { style: "currency", currencyDisplay: "code" }); // e.g. "USD"
  58. Name, // Intl.NumberFormat(locale, { style: "currency", currencyDisplay: "name" }); // e.g. "US dollar"
  59. Max,
  60. Default = Symbol,
  61. };
  62. enum class CollatorSensitivity
  63. {
  64. Base,
  65. Accent,
  66. Case,
  67. Variant,
  68. Max,
  69. Default = Variant,
  70. };
  71. enum class CollatorCaseFirst
  72. {
  73. Upper,
  74. Lower,
  75. False,
  76. Max,
  77. Default = False,
  78. };
  79. #pragma warning(push)
  80. #pragma warning(disable:4309) // truncation of constant value
  81. #pragma warning(disable:4838) // conversion from 'int' to 'const char' requires a narrowing conversion
  82. #if DISABLE_JIT
  83. #if TARGET_64
  84. #include "InJavascript/Intl.js.nojit.bc.64b.h"
  85. #else
  86. #include "InJavascript/Intl.js.nojit.bc.32b.h"
  87. #endif
  88. #else
  89. #if TARGET_64
  90. #include "InJavascript/Intl.js.bc.64b.h"
  91. #else
  92. #include "InJavascript/Intl.js.bc.32b.h"
  93. #endif
  94. #endif
  95. #pragma warning(pop)
  96. #define IfFailAssertAndThrowHr(op) \
  97. if (FAILED(hr=(op))) \
  98. { \
  99. AssertMsg(false, "HRESULT was a failure."); \
  100. JavascriptError::MapAndThrowError(scriptContext, hr); \
  101. } \
  102. #define IfFailAssertMsgAndThrowHr(op, msg) \
  103. if (FAILED(hr=(op))) \
  104. { \
  105. AssertMsg(false, msg); \
  106. JavascriptError::MapAndThrowError(scriptContext, hr); \
  107. } \
  108. #ifdef INTL_WINGLOB
  109. #define TO_JSBOOL(sc, b) ((b) ? (sc)->GetLibrary()->GetTrue() : (sc)->GetLibrary()->GetFalse())
  110. #define IfCOMFailIgnoreSilentlyAndReturn(op) \
  111. if(FAILED(hr=(op))) \
  112. { \
  113. return; \
  114. } \
  115. #define HandleOOMSOEHR(hr) \
  116. if (hr == E_OUTOFMEMORY) \
  117. { \
  118. JavascriptError::ThrowOutOfMemoryError(scriptContext); \
  119. } \
  120. else if(hr == VBSERR_OutOfStack) \
  121. { \
  122. JavascriptError::ThrowStackOverflowError(scriptContext); \
  123. } \
  124. #define IfFailThrowHr(op) \
  125. if (FAILED(hr=(op))) \
  126. { \
  127. JavascriptError::MapAndThrowError(scriptContext, hr); \
  128. } \
  129. #define SetPropertyOn(obj, propID, value) \
  130. obj->SetProperty(propID, value, Js::PropertyOperationFlags::PropertyOperation_None, nullptr) \
  131. #define SetStringPropertyOn(obj, propID, propValue) \
  132. SetPropertyOn(obj, propID, Js::JavascriptString::NewCopySz(propValue, scriptContext)) \
  133. #define SetPropertyLOn(obj, literalProperty, value) \
  134. obj->SetProperty(Js::JavascriptString::NewCopySz(literalProperty, scriptContext), value, Js::PropertyOperationFlags::PropertyOperation_None, nullptr) \
  135. #define SetStringPropertyLOn(obj, literalProperty, propValue) \
  136. SetPropertyLOn(obj, literalProperty, Js::JavascriptString::NewCopySz(propValue, scriptContext)) \
  137. #define SetPropertyBuiltInOn(obj, builtInPropID, value) \
  138. SetPropertyOn(obj, Js::PropertyIds::builtInPropID, value) \
  139. #define SetStringPropertyBuiltInOn(obj, builtInPropID, propValue) \
  140. SetPropertyBuiltInOn(obj, builtInPropID, Js::JavascriptString::NewCopySz(propValue, scriptContext))
  141. #define GetPropertyFrom(obj, propertyID) \
  142. Js::JavascriptOperators::GetProperty(obj, propertyID, &propertyValue, scriptContext) \
  143. #define GetPropertyLFrom(obj, propertyName) \
  144. GetPropertyFrom(obj, scriptContext->GetOrAddPropertyIdTracked(propertyName, wcslen(propertyName)))
  145. #define GetPropertyBuiltInFrom(obj, builtInPropID) \
  146. GetPropertyFrom(obj, Js::PropertyIds::builtInPropID) \
  147. #define GetTypedPropertyBuiltInFrom(obj, builtInPropID, Type) \
  148. (GetPropertyFrom(obj, Js::PropertyIds::builtInPropID) && Type::Is(propertyValue)) \
  149. #define HasPropertyOn(obj, propID) \
  150. Js::JavascriptOperators::HasProperty(obj, propID) \
  151. #define HasPropertyBuiltInOn(obj, builtInPropID) \
  152. HasPropertyOn(obj, Js::PropertyIds::builtInPropID) \
  153. #define HasPropertyLOn(obj, propertyName) \
  154. HasPropertyOn(obj, scriptContext->GetOrAddPropertyIdTracked(propertyName, wcslen(propertyName)))
  155. #define SetHSTRINGPropertyOn(obj, propID, hstringValue) \
  156. SetStringPropertyOn(obj, propID, wgl->WindowsGetStringRawBuffer(hstringValue, &length)) \
  157. #define SetHSTRINGPropertyLOn(obj, literalProperty, hstringValue) \
  158. SetStringPropertyLOn(obj, literalProperty, wgl->WindowsGetStringRawBuffer(hstringValue, &length)) \
  159. #define SetHSTRINGPropertyBuiltInOn(obj, builtInPropID, hstringValue) \
  160. SetStringPropertyBuiltInOn(obj, builtInPropID, wgl->WindowsGetStringRawBuffer(hstringValue, &length)) \
  161. #endif
  162. #define INTL_CHECK_ARGS(argcheck) AssertOrFailFastMsg((argcheck), "Intl platform function given bad arguments")
  163. namespace Js
  164. {
  165. #ifdef ENABLE_INTL_OBJECT
  166. #ifdef INTL_WINGLOB
  167. class AutoHSTRING
  168. {
  169. PREVENT_COPY(AutoHSTRING)
  170. private:
  171. HSTRING value;
  172. public:
  173. HSTRING *operator&() { Assert(value == nullptr); return &value; }
  174. HSTRING operator*() const { Assert(value != nullptr); return value; }
  175. AutoHSTRING()
  176. : value(nullptr)
  177. { }
  178. ~AutoHSTRING()
  179. {
  180. Clear();
  181. }
  182. void Clear()
  183. {
  184. if (value != nullptr)
  185. {
  186. WindowsDeleteString(value);
  187. value = nullptr;
  188. }
  189. }
  190. };
  191. #endif
  192. // Defining Finalizable wrappers for Intl data
  193. #if defined(INTL_WINGLOB)
  194. class AutoCOMJSObject : public FinalizableObject
  195. {
  196. IInspectable *instance;
  197. public:
  198. DEFINE_VTABLE_CTOR_NOBASE(AutoCOMJSObject);
  199. AutoCOMJSObject(IInspectable *object)
  200. : instance(object)
  201. { }
  202. static AutoCOMJSObject * New(Recycler * recycler, IInspectable *object)
  203. {
  204. return RecyclerNewFinalized(recycler, AutoCOMJSObject, object);
  205. }
  206. void Finalize(bool isShutdown) override
  207. {
  208. }
  209. void Dispose(bool isShutdown) override
  210. {
  211. if (!isShutdown)
  212. {
  213. instance->Release();
  214. }
  215. }
  216. void Mark(Recycler * recycler) override
  217. {
  218. }
  219. IInspectable *GetInstance()
  220. {
  221. return instance;
  222. }
  223. };
  224. #elif defined(INTL_ICU)
  225. template<typename TResource, void(__cdecl * CloseFunction)(TResource)>
  226. class FinalizableICUObject : public FinalizableObject
  227. {
  228. private:
  229. FieldNoBarrier(TResource) resource;
  230. public:
  231. FinalizableICUObject(TResource resource) : resource(resource)
  232. {
  233. }
  234. static FinalizableICUObject<TResource, CloseFunction> *New(Recycler *recycler, TResource resource)
  235. {
  236. return RecyclerNewFinalized(recycler, FinalizableICUObject, resource);
  237. }
  238. TResource GetInstance()
  239. {
  240. return resource;
  241. }
  242. operator TResource()
  243. {
  244. return resource;
  245. }
  246. void Finalize(bool isShutdown) override
  247. {
  248. }
  249. void Dispose(bool isShutdown) override
  250. {
  251. if (!isShutdown)
  252. {
  253. CloseFunction(resource);
  254. }
  255. }
  256. void Mark(Recycler *recycler) override
  257. {
  258. }
  259. };
  260. typedef FinalizableICUObject<UNumberFormat *, unum_close> FinalizableUNumberFormat;
  261. typedef FinalizableICUObject<UDateFormat *, udat_close> FinalizableUDateFormat;
  262. typedef FinalizableICUObject<UFieldPositionIterator *, ufieldpositer_close> FinalizableUFieldPositionIterator;
  263. typedef FinalizableICUObject<UCollator *, ucol_close> FinalizableUCollator;
  264. typedef FinalizableICUObject<UPluralRules *, uplrules_close> FinalizableUPluralRules;
  265. template<typename TExecutor>
  266. static void EnsureBuffer(_In_ TExecutor executor, _In_ Recycler *recycler, _Outptr_result_buffer_(*returnLength) char16 **ret, _Out_ int *returnLength, _In_ bool allowZeroLengthStrings = false, _In_ int firstTryLength = 8)
  267. {
  268. UErrorCode status = U_ZERO_ERROR;
  269. *ret = RecyclerNewArrayLeaf(recycler, char16, firstTryLength);
  270. *returnLength = executor(reinterpret_cast<UChar *>(*ret), firstTryLength, &status);
  271. AssertOrFailFast(allowZeroLengthStrings ? *returnLength >= 0 : *returnLength > 0);
  272. if (ICU_BUFFER_FAILURE(status))
  273. {
  274. AssertOrFailFastMsg(*returnLength >= firstTryLength, "Executor reported buffer failure but did not require additional space");
  275. int secondTryLength = *returnLength + 1;
  276. INTL_TRACE("Buffer of length %d was too short, retrying with buffer of length %d", firstTryLength, secondTryLength);
  277. status = U_ZERO_ERROR;
  278. *ret = RecyclerNewArrayLeaf(recycler, char16, secondTryLength);
  279. *returnLength = executor(reinterpret_cast<UChar *>(*ret), secondTryLength, &status);
  280. AssertOrFailFastMsg(*returnLength == secondTryLength - 1, "Second try of executor returned unexpected length");
  281. }
  282. else
  283. {
  284. AssertOrFailFastMsg(*returnLength < firstTryLength, "Executor required additional length but reported successful status");
  285. }
  286. AssertOrFailFastMsg(!ICU_FAILURE(status), ICU_ERRORMESSAGE(status));
  287. }
  288. template <typename T>
  289. static T *AssertProperty(_In_ DynamicObject *state, _In_ PropertyIds propertyId)
  290. {
  291. Var propertyValue = nullptr;
  292. JavascriptOperators::GetProperty(state, propertyId, &propertyValue, state->GetScriptContext());
  293. AssertOrFailFast(propertyValue && T::Is(propertyValue));
  294. return T::UnsafeFromVar(propertyValue);
  295. }
  296. static JavascriptString *AssertStringProperty(_In_ DynamicObject *state, _In_ PropertyIds propertyId)
  297. {
  298. return AssertProperty<JavascriptString>(state, propertyId);
  299. }
  300. static int AssertIntegerProperty(_In_ DynamicObject *state, _In_ PropertyIds propertyId)
  301. {
  302. Var propertyValue = nullptr;
  303. JavascriptOperators::GetProperty(state, propertyId, &propertyValue, state->GetScriptContext());
  304. AssertOrFailFast(propertyValue);
  305. if (TaggedInt::Is(propertyValue))
  306. {
  307. return TaggedInt::ToInt32(propertyValue);
  308. }
  309. else
  310. {
  311. AssertOrFailFast(JavascriptNumber::Is(propertyValue));
  312. int ret;
  313. AssertOrFailFast(JavascriptNumber::TryGetInt32Value(JavascriptNumber::GetValue(propertyValue), &ret));
  314. return ret;
  315. }
  316. }
  317. static bool AssertBooleanProperty(_In_ DynamicObject *state, _In_ PropertyIds propertyId)
  318. {
  319. return AssertProperty<JavascriptBoolean>(state, propertyId)->GetValue();
  320. }
  321. template <typename T>
  322. static T AssertEnumProperty(_In_ DynamicObject *state, _In_ PropertyIds propertyId)
  323. {
  324. int p = AssertIntegerProperty(state, propertyId);
  325. T ret = static_cast<T>(p);
  326. AssertMsg(p >= 0 && ret < T::Max, "Invalid value for enum property");
  327. return ret;
  328. }
  329. template <typename T>
  330. static _Ret_notnull_ T ThrowOOMIfNull(_In_ T value)
  331. {
  332. if (value == nullptr)
  333. {
  334. Throw::OutOfMemory();
  335. }
  336. return value;
  337. }
  338. template <size_t N>
  339. static void LangtagToLocaleID(_In_count_(langtagLength) const char16 *langtag, _In_ charcount_t langtagLength, _Out_ char(&localeID)[N])
  340. {
  341. static_assert(N >= ULOC_FULLNAME_CAPACITY, "LocaleID must be large enough to fit the largest possible ICU localeID");
  342. UErrorCode status = U_ZERO_ERROR;
  343. utf8::WideToNarrow langtag8(langtag, langtagLength);
  344. int32_t localeIDLength = 0;
  345. uloc_forLanguageTag(langtag8, localeID, N, &localeIDLength, &status);
  346. ICU_ASSERT(status, localeIDLength > 0 && static_cast<size_t>(localeIDLength) < N);
  347. }
  348. template <size_t N>
  349. static void LangtagToLocaleID(_In_ JavascriptString *langtag, _Out_ char(&localeID)[N])
  350. {
  351. LangtagToLocaleID(langtag->GetSz(), langtag->GetLength(), localeID);
  352. }
  353. template <typename Callback>
  354. static void ForEachUEnumeration(UEnumeration *enumeration, Callback callback)
  355. {
  356. int valueLength = 0;
  357. UErrorCode status = U_ZERO_ERROR;
  358. for (int index = 0, const char *value = uenum_next(enumeration, &valueLength, &status); value != nullptr; index++, value = uenum_next(enumeration, &valueLength, &status))
  359. {
  360. ICU_ASSERT(status, valueLength > 0);
  361. // cast valueLength now since we have verified its greater than 0
  362. callback(index, value, static_cast<charcount_t>(valueLength));
  363. }
  364. }
  365. template <typename Callback>
  366. static void ForEachUEnumeration16(UEnumeration *enumeration, Callback callback)
  367. {
  368. int valueLength = 0;
  369. UErrorCode status = U_ZERO_ERROR;
  370. int index = 0;
  371. for (const UChar *value = uenum_unext(enumeration, &valueLength, &status); value != nullptr; index++, value = uenum_unext(enumeration, &valueLength, &status))
  372. {
  373. ICU_ASSERT(status, valueLength > 0);
  374. // cast valueLength now since we have verified its greater than 0
  375. callback(index, reinterpret_cast<const char16 *>(value), static_cast<charcount_t>(valueLength));
  376. }
  377. }
  378. #endif
  379. IntlEngineInterfaceExtensionObject::IntlEngineInterfaceExtensionObject(Js::ScriptContext* scriptContext) :
  380. EngineExtensionObjectBase(EngineInterfaceExtensionKind_Intl, scriptContext),
  381. dateToLocaleString(nullptr),
  382. dateToLocaleTimeString(nullptr),
  383. dateToLocaleDateString(nullptr),
  384. numberToLocaleString(nullptr),
  385. stringLocaleCompare(nullptr),
  386. intlNativeInterfaces(nullptr),
  387. intlByteCode(nullptr),
  388. wasInitialized(false)
  389. {
  390. }
  391. // Initializes the IntlEngineInterfaceExtensionObject::EntryInfo struct
  392. #ifdef INTL_ENTRY
  393. #undef INTL_ENTRY
  394. #endif
  395. #define INTL_ENTRY(id, func) \
  396. NoProfileFunctionInfo IntlEngineInterfaceExtensionObject::EntryInfo::Intl_##func##(FORCE_NO_WRITE_BARRIER_TAG(IntlEngineInterfaceExtensionObject::EntryIntl_##func##));
  397. #include "IntlExtensionObjectBuiltIns.h"
  398. #undef INTL_ENTRY
  399. #ifdef INTL_WINGLOB
  400. WindowsGlobalizationAdapter* IntlEngineInterfaceExtensionObject::GetWindowsGlobalizationAdapter(_In_ ScriptContext * scriptContext)
  401. {
  402. return scriptContext->GetThreadContext()->GetWindowsGlobalizationAdapter();
  403. }
  404. #endif
  405. void IntlEngineInterfaceExtensionObject::Initialize()
  406. {
  407. if (wasInitialized)
  408. {
  409. return;
  410. }
  411. JavascriptLibrary* library = scriptContext->GetLibrary();
  412. // Ensure JsBuiltIns are initialized before initializing Intl which uses some of them.
  413. library->EnsureBuiltInEngineIsReady();
  414. DynamicObject* commonObject = library->GetEngineInterfaceObject()->GetCommonNativeInterfaces();
  415. if (scriptContext->IsIntlEnabled())
  416. {
  417. Assert(library->GetEngineInterfaceObject() != nullptr);
  418. this->intlNativeInterfaces = DynamicObject::New(library->GetRecycler(),
  419. DynamicType::New(scriptContext, TypeIds_Object, commonObject, nullptr,
  420. DeferredTypeHandler<InitializeIntlNativeInterfaces>::GetDefaultInstance()));
  421. library->AddMember(library->GetEngineInterfaceObject(), Js::PropertyIds::Intl, this->intlNativeInterfaces);
  422. // Only show the platform object publicly if -IntlPlatform is passed
  423. if (CONFIG_FLAG(IntlPlatform))
  424. {
  425. library->AddMember(library->GetIntlObject(), PropertyIds::platform, this->intlNativeInterfaces);
  426. }
  427. }
  428. wasInitialized = true;
  429. }
  430. #if DBG
  431. void IntlEngineInterfaceExtensionObject::DumpByteCode()
  432. {
  433. Output::Print(_u("Dumping Intl Byte Code:"));
  434. Assert(this->intlByteCode);
  435. Js::ByteCodeDumper::DumpRecursively(intlByteCode);
  436. }
  437. #endif
  438. bool IntlEngineInterfaceExtensionObject::InitializeIntlNativeInterfaces(DynamicObject* intlNativeInterfaces, DeferredTypeHandlerBase * typeHandler, DeferredInitializeMode mode)
  439. {
  440. typeHandler->Convert(intlNativeInterfaces, mode, 16);
  441. ScriptContext* scriptContext = intlNativeInterfaces->GetScriptContext();
  442. JavascriptLibrary* library = scriptContext->GetLibrary();
  443. // gives each entrypoint a property ID on the intlNativeInterfaces library object
  444. #ifdef INTL_ENTRY
  445. #undef INTL_ENTRY
  446. #endif
  447. #define INTL_ENTRY(id, func) \
  448. library->AddFunctionToLibraryObject(intlNativeInterfaces, Js::PropertyIds::##id, &IntlEngineInterfaceExtensionObject::EntryInfo::Intl_##func, 1);
  449. #include "IntlExtensionObjectBuiltIns.h"
  450. #undef INTL_ENTRY
  451. library->AddMember(intlNativeInterfaces, PropertyIds::FallbackSymbol, library->CreateSymbol(BuiltInPropertyRecords::_intlFallbackSymbol));
  452. #if INTL_WINGLOB
  453. library->AddMember(intlNativeInterfaces, Js::PropertyIds::winglob, library->GetTrue());
  454. #else
  455. library->AddMember(intlNativeInterfaces, Js::PropertyIds::winglob, library->GetFalse());
  456. // when using ICU, we can call ulocdata_getCLDRVersion to ensure that ICU is functioning properly before allowing Intl to continue.
  457. // ulocdata_getCLDRVersion will cause the data file to be loaded, and if we don't have enough memory to do so, we can throw OutOfMemory here.
  458. // This is to protect against spurious U_MISSING_RESOURCE_ERRORs and U_FILE_ACCESS_ERRORs coming from early-lifecycle
  459. // functions that require ICU data.
  460. // See OS#16897150, OS#16896933, and others relating to bad statuses returned by GetLocaleData and IsLocaleAvailable
  461. // This was initially attempted using u_init, however u_init does not work with Node's default small-icu data file
  462. // because it contains no converters.
  463. UErrorCode status = U_ZERO_ERROR;
  464. UVersionInfo cldrVersion;
  465. ulocdata_getCLDRVersion(cldrVersion, &status);
  466. if (status == U_MEMORY_ALLOCATION_ERROR || status == U_FILE_ACCESS_ERROR || status == U_MISSING_RESOURCE_ERROR)
  467. {
  468. // Trace that this happens in case there are build system changes that actually cause the data file to be not found
  469. INTL_TRACE("Could not initialize ICU - ulocdata_getCLDRVersion returned status %S", u_errorName(status));
  470. Throw::OutOfMemory();
  471. }
  472. else
  473. {
  474. INTL_TRACE("Using CLDR version %d.%d.%d.%d", cldrVersion[0], cldrVersion[1], cldrVersion[2], cldrVersion[3]);
  475. }
  476. AssertOrFailFastMsg(U_SUCCESS(status), "ulocdata_getCLDRVersion returned non-OOM failure");
  477. #endif // else !INTL_WINGLOB
  478. intlNativeInterfaces->SetHasNoEnumerableProperties(true);
  479. return true;
  480. }
  481. void IntlEngineInterfaceExtensionObject::deletePrototypePropertyHelper(ScriptContext* scriptContext, DynamicObject* intlObject, Js::PropertyId objectPropertyId, Js::PropertyId getterFunctionId)
  482. {
  483. DynamicObject *prototypeObject = nullptr;
  484. DynamicObject *functionObj = nullptr;
  485. Var propertyValue = nullptr;
  486. Var prototypeValue = nullptr;
  487. Var resolvedOptionsValue = nullptr;
  488. Var getter = nullptr;
  489. Var setter = nullptr;
  490. if (!JavascriptOperators::GetProperty(intlObject, objectPropertyId, &propertyValue, scriptContext) ||
  491. !JavascriptOperators::IsObject(propertyValue))
  492. {
  493. return;
  494. }
  495. if (!JavascriptOperators::GetProperty(DynamicObject::FromVar(propertyValue), Js::PropertyIds::prototype, &prototypeValue, scriptContext) ||
  496. !JavascriptOperators::IsObject(prototypeValue))
  497. {
  498. return;
  499. }
  500. prototypeObject = DynamicObject::FromVar(prototypeValue);
  501. if (!JavascriptOperators::GetProperty(prototypeObject, Js::PropertyIds::resolvedOptions, &resolvedOptionsValue, scriptContext) ||
  502. !JavascriptOperators::IsObject(resolvedOptionsValue))
  503. {
  504. return;
  505. }
  506. functionObj = DynamicObject::FromVar(resolvedOptionsValue);
  507. functionObj->SetConfigurable(Js::PropertyIds::prototype, true);
  508. functionObj->DeleteProperty(Js::PropertyIds::prototype, Js::PropertyOperationFlags::PropertyOperation_None);
  509. if (!JavascriptOperators::GetOwnAccessors(prototypeObject, getterFunctionId, &getter, &setter, scriptContext) ||
  510. !JavascriptOperators::IsObject(getter))
  511. {
  512. return;
  513. }
  514. functionObj = DynamicObject::FromVar(getter);
  515. functionObj->SetConfigurable(Js::PropertyIds::prototype, true);
  516. functionObj->DeleteProperty(Js::PropertyIds::prototype, Js::PropertyOperationFlags::PropertyOperation_None);
  517. }
  518. void IntlEngineInterfaceExtensionObject::cleanUpIntl(ScriptContext *scriptContext, DynamicObject* intlObject)
  519. {
  520. this->dateToLocaleString = nullptr;
  521. this->dateToLocaleTimeString = nullptr;
  522. this->dateToLocaleDateString = nullptr;
  523. this->numberToLocaleString = nullptr;
  524. this->stringLocaleCompare = nullptr;
  525. //Failed to setup Intl; Windows.Globalization.dll is most likely missing.
  526. if (Js::JavascriptOperators::HasProperty(intlObject, Js::PropertyIds::Collator))
  527. {
  528. intlObject->DeleteProperty(Js::PropertyIds::Collator, Js::PropertyOperationFlags::PropertyOperation_None);
  529. }
  530. if (Js::JavascriptOperators::HasProperty(intlObject, Js::PropertyIds::NumberFormat))
  531. {
  532. intlObject->DeleteProperty(Js::PropertyIds::NumberFormat, Js::PropertyOperationFlags::PropertyOperation_None);
  533. }
  534. if (Js::JavascriptOperators::HasProperty(intlObject, Js::PropertyIds::DateTimeFormat))
  535. {
  536. intlObject->DeleteProperty(Js::PropertyIds::DateTimeFormat, Js::PropertyOperationFlags::PropertyOperation_None);
  537. }
  538. }
  539. void IntlEngineInterfaceExtensionObject::EnsureIntlByteCode(_In_ ScriptContext * scriptContext)
  540. {
  541. if (this->intlByteCode == nullptr)
  542. {
  543. SourceContextInfo * sourceContextInfo = scriptContext->GetSourceContextInfo(Js::Constants::NoHostSourceContext, NULL);
  544. Assert(sourceContextInfo != nullptr);
  545. SRCINFO si;
  546. memset(&si, 0, sizeof(si));
  547. si.sourceContextInfo = sourceContextInfo;
  548. SRCINFO *hsi = scriptContext->AddHostSrcInfo(&si);
  549. uint32 flags = fscrIsLibraryCode | (CONFIG_FLAG(CreateFunctionProxy) && !scriptContext->IsProfiling() ? fscrAllowFunctionProxy : 0);
  550. HRESULT hr = Js::ByteCodeSerializer::DeserializeFromBuffer(scriptContext, flags, (LPCUTF8)nullptr, hsi, (byte*)Library_Bytecode_Intl, nullptr, &this->intlByteCode);
  551. IfFailAssertMsgAndThrowHr(hr, "Failed to deserialize Intl.js bytecode - very probably the bytecode needs to be rebuilt.");
  552. this->SetHasBytecode();
  553. }
  554. }
  555. void IntlEngineInterfaceExtensionObject::InjectIntlLibraryCode(_In_ ScriptContext * scriptContext, DynamicObject* intlObject, IntlInitializationType intlInitializationType)
  556. {
  557. JavascriptExceptionObject *pExceptionObject = nullptr;
  558. #ifdef INTL_WINGLOB
  559. WindowsGlobalizationAdapter* globAdapter = GetWindowsGlobalizationAdapter(scriptContext);
  560. #endif
  561. try {
  562. this->EnsureIntlByteCode(scriptContext);
  563. Assert(intlByteCode != nullptr);
  564. #ifdef INTL_WINGLOB
  565. DelayLoadWindowsGlobalization *library = scriptContext->GetThreadContext()->GetWindowsGlobalizationLibrary();
  566. #endif
  567. JavascriptString* initType = nullptr;
  568. #ifdef INTL_WINGLOB
  569. HRESULT hr;
  570. //Ensure we have initialized all appropriate COM objects for the adapter (we will be using them now)
  571. IfCOMFailIgnoreSilentlyAndReturn(globAdapter->EnsureCommonObjectsInitialized(library));
  572. #endif
  573. switch (intlInitializationType)
  574. {
  575. default:
  576. AssertMsg(false, "Not a valid intlInitializationType.");
  577. // fall thru
  578. case IntlInitializationType::Intl:
  579. #ifdef INTL_WINGLOB
  580. IfCOMFailIgnoreSilentlyAndReturn(globAdapter->EnsureNumberFormatObjectsInitialized(library));
  581. IfCOMFailIgnoreSilentlyAndReturn(globAdapter->EnsureDateTimeFormatObjectsInitialized(library));
  582. #endif
  583. initType = scriptContext->GetPropertyString(PropertyIds::Intl);
  584. break;
  585. case IntlInitializationType::StringPrototype:
  586. // No other windows globalization adapter needed. Common adapter should suffice
  587. initType = scriptContext->GetPropertyString(PropertyIds::String);
  588. break;
  589. case IntlInitializationType::DatePrototype:
  590. #ifdef INTL_WINGLOB
  591. IfCOMFailIgnoreSilentlyAndReturn(globAdapter->EnsureDateTimeFormatObjectsInitialized(library));
  592. #endif
  593. initType = scriptContext->GetPropertyString(PropertyIds::Date);
  594. break;
  595. case IntlInitializationType::NumberPrototype:
  596. #ifdef INTL_WINGLOB
  597. IfCOMFailIgnoreSilentlyAndReturn(globAdapter->EnsureNumberFormatObjectsInitialized(library));
  598. #endif
  599. initType = scriptContext->GetPropertyString(PropertyIds::Number);
  600. break;
  601. }
  602. Js::ScriptFunction *function = scriptContext->GetLibrary()->CreateScriptFunction(intlByteCode->GetNestedFunctionForExecution(0));
  603. #ifdef ENABLE_SCRIPT_PROFILING
  604. // If we are profiling, we need to register the script to the profiler callback, so the script compiled event will be sent.
  605. if (scriptContext->IsProfiling())
  606. {
  607. scriptContext->RegisterScript(function->GetFunctionProxy());
  608. }
  609. #endif
  610. #ifdef ENABLE_SCRIPT_DEBUGGING
  611. // Mark we are profiling library code already, so that any initialization library code called here won't be reported to profiler.
  612. // Also tell the debugger not to record events during intialization so that we don't leak information about initialization.
  613. AutoInitLibraryCodeScope autoInitLibraryCodeScope(scriptContext);
  614. #endif
  615. Js::Var args[] = { scriptContext->GetLibrary()->GetUndefined(), scriptContext->GetLibrary()->GetEngineInterfaceObject(), initType };
  616. Js::CallInfo callInfo(Js::CallFlags_Value, _countof(args));
  617. Js::Arguments arguments(callInfo, args);
  618. scriptContext->GetThreadContext()->ExecuteImplicitCall(function, Js::ImplicitCall_Accessor, [=]()->Js::Var
  619. {
  620. return JavascriptFunction::CallRootFunctionInScript(function, arguments);
  621. });
  622. // Delete prototypes on functions if initialized Intl object
  623. if (intlInitializationType == IntlInitializationType::Intl)
  624. {
  625. deletePrototypePropertyHelper(scriptContext, intlObject, Js::PropertyIds::Collator, Js::PropertyIds::compare);
  626. deletePrototypePropertyHelper(scriptContext, intlObject, Js::PropertyIds::NumberFormat, Js::PropertyIds::format);
  627. deletePrototypePropertyHelper(scriptContext, intlObject, Js::PropertyIds::DateTimeFormat, Js::PropertyIds::format);
  628. }
  629. #if DBG_DUMP
  630. if (PHASE_DUMP(Js::ByteCodePhase, function->GetFunctionProxy()) && Js::Configuration::Global.flags.Verbose)
  631. {
  632. DumpByteCode();
  633. }
  634. #endif
  635. }
  636. catch (const JavascriptException& err)
  637. {
  638. pExceptionObject = err.GetAndClear();
  639. }
  640. if (pExceptionObject)
  641. {
  642. if (intlInitializationType == IntlInitializationType::Intl)
  643. {
  644. cleanUpIntl(scriptContext, intlObject);
  645. }
  646. if (pExceptionObject == ThreadContext::GetContextForCurrentThread()->GetPendingOOMErrorObject() ||
  647. pExceptionObject == ThreadContext::GetContextForCurrentThread()->GetPendingSOErrorObject())
  648. {
  649. // Reset factory objects that are might not have fully initialized
  650. #ifdef INTL_WINGLOB
  651. globAdapter->ResetCommonFactoryObjects();
  652. #endif
  653. switch (intlInitializationType) {
  654. default:
  655. AssertMsg(false, "Not a valid intlInitializationType.");
  656. // fall thru
  657. case IntlInitializationType::Intl:
  658. #ifdef INTL_WINGLOB
  659. globAdapter->ResetNumberFormatFactoryObjects();
  660. globAdapter->ResetDateTimeFormatFactoryObjects();
  661. #endif
  662. scriptContext->GetLibrary()->ResetIntlObject();
  663. break;
  664. case IntlInitializationType::StringPrototype:
  665. // No other windows globalization adapter is created. Resetting common adapter should suffice
  666. break;
  667. case IntlInitializationType::DatePrototype:
  668. #ifdef INTL_WINGLOB
  669. globAdapter->ResetDateTimeFormatFactoryObjects();
  670. #endif
  671. break;
  672. case IntlInitializationType::NumberPrototype:
  673. #ifdef INTL_WINGLOB
  674. globAdapter->ResetNumberFormatFactoryObjects();
  675. #endif
  676. break;
  677. }
  678. JavascriptExceptionOperators::DoThrowCheckClone(pExceptionObject, scriptContext);
  679. }
  680. #if DEBUG
  681. JavascriptExceptionOperators::DoThrowCheckClone(pExceptionObject, scriptContext);
  682. #else
  683. JavascriptError::ThrowTypeError(scriptContext, JSERR_IntlNotAvailable);
  684. #endif
  685. }
  686. }
  687. // First parameter is boolean.
  688. Var IntlEngineInterfaceExtensionObject::EntryIntl_RaiseAssert(RecyclableObject* function, CallInfo callInfo, ...)
  689. {
  690. EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
  691. if (args.Info.Count < 2 || !JavascriptError::Is(args.Values[1]))
  692. {
  693. AssertMsg(false, "Intl's Assert platform API was called incorrectly.");
  694. return scriptContext->GetLibrary()->GetUndefined();
  695. }
  696. #if DEBUG
  697. #ifdef INTL_ICU_DEBUG
  698. Output::Print(_u("EntryIntl_RaiseAssert\n"));
  699. #endif
  700. JavascriptExceptionOperators::Throw(JavascriptError::FromVar(args.Values[1]), scriptContext);
  701. #else
  702. return scriptContext->GetLibrary()->GetUndefined();
  703. #endif
  704. }
  705. Var IntlEngineInterfaceExtensionObject::EntryIntl_IsWellFormedLanguageTag(RecyclableObject* function, CallInfo callInfo, ...)
  706. {
  707. #if defined(INTL_ICU)
  708. AssertOrFailFastMsg(false, "IsWellFormedLanguageTag is not implemented using ICU");
  709. return nullptr;
  710. #else
  711. EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
  712. if (args.Info.Count < 2 || !JavascriptString::Is(args.Values[1]))
  713. {
  714. // IsWellFormedLanguageTag of undefined or non-string is false
  715. return scriptContext->GetLibrary()->GetFalse();
  716. }
  717. JavascriptString *argString = JavascriptString::FromVar(args.Values[1]);
  718. return TO_JSBOOL(scriptContext, GetWindowsGlobalizationAdapter(scriptContext)->IsWellFormedLanguageTag(scriptContext, argString->GetSz()));
  719. #endif
  720. }
  721. Var IntlEngineInterfaceExtensionObject::EntryIntl_NormalizeLanguageTag(RecyclableObject* function, CallInfo callInfo, ...)
  722. {
  723. EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
  724. #if defined(INTL_ICU)
  725. INTL_CHECK_ARGS(args.Info.Count == 2 && JavascriptString::Is(args[1]));
  726. UErrorCode status = U_ZERO_ERROR;
  727. JavascriptString *langtag = JavascriptString::UnsafeFromVar(args[1]);
  728. utf8::WideToNarrow langtag8(langtag->GetSz(), langtag->GetLength());
  729. // ICU doesn't have a full-fledged canonicalization implementation that correctly replaces all preferred values
  730. // and grandfathered tags, as required by #sec-canonicalizelanguagetag.
  731. // However, passing the locale through uloc_forLanguageTag -> uloc_toLanguageTag gets us most of the way there
  732. // by replacing some(?) values, correctly capitalizing the tag, and re-ordering extensions
  733. int parsedLength = 0;
  734. char localeID[ULOC_FULLNAME_CAPACITY] = { 0 };
  735. int forLangTagResultLength = uloc_forLanguageTag(langtag8, localeID, ULOC_FULLNAME_CAPACITY, &parsedLength, &status);
  736. AssertOrFailFast(parsedLength >= 0);
  737. if (status == U_ILLEGAL_ARGUMENT_ERROR || ((charcount_t) parsedLength) < langtag->GetLength())
  738. {
  739. // The string passed in to NormalizeLanguageTag has already passed IsStructurallyValidLanguageTag.
  740. // However, duplicate unicode extension keys, such as "de-u-co-phonebk-co-phonebk", are structurally
  741. // valid according to RFC5646 yet still trigger U_ILLEGAL_ARGUMENT_ERROR
  742. // V8 ~6.2 says that the above language tag is invalid, while SpiderMonkey ~58 handles it.
  743. // Until we have a more spec-compliant implementation of CanonicalizeLanguageTag, err on the side
  744. // of caution and say it is invalid.
  745. // We also check for parsedLength < langtag->GetLength() because there are cases when status == U_ZERO_ERROR
  746. // but the langtag was not valid, such as "en-tesTER-TESter" (OSS-Fuzz #6657).
  747. // NOTE: make sure we check for `undefined` at the platform.normalizeLanguageTag callsite.
  748. return scriptContext->GetLibrary()->GetUndefined();
  749. }
  750. // forLangTagResultLength can be 0 if langtag is "und".
  751. // uloc_toLanguageTag("") returns "und", so this works out (forLanguageTag can return >= 0 but toLanguageTag must return > 0)
  752. ICU_ASSERT(status, forLangTagResultLength >= 0 && ((charcount_t) parsedLength) == langtag->GetLength());
  753. char canonicalized[ULOC_FULLNAME_CAPACITY] = { 0 };
  754. int toLangTagResultLength = uloc_toLanguageTag(localeID, canonicalized, ULOC_FULLNAME_CAPACITY, true, &status);
  755. ICU_ASSERT(status, toLangTagResultLength > 0);
  756. // allocate toLangTagResultLength + 1 to leave room for null terminator
  757. char16 *canonicalized16 = RecyclerNewArrayLeaf(scriptContext->GetRecycler(), char16, toLangTagResultLength + 1);
  758. charcount_t canonicalized16Len = 0;
  759. HRESULT hr = utf8::NarrowStringToWideNoAlloc(
  760. canonicalized,
  761. toLangTagResultLength,
  762. canonicalized16,
  763. toLangTagResultLength + 1,
  764. &canonicalized16Len
  765. );
  766. AssertOrFailFast(hr == S_OK && ((int) canonicalized16Len) == toLangTagResultLength);
  767. return JavascriptString::NewWithBuffer(canonicalized16, toLangTagResultLength, scriptContext);
  768. #else
  769. if (args.Info.Count < 2 || !JavascriptString::Is(args.Values[1]))
  770. {
  771. // NormalizeLanguageTag of undefined or non-string is undefined
  772. return scriptContext->GetLibrary()->GetUndefined();
  773. }
  774. JavascriptString *argString = JavascriptString::FromVar(args.Values[1]);
  775. JavascriptString *retVal;
  776. HRESULT hr;
  777. AutoHSTRING str;
  778. hr = GetWindowsGlobalizationAdapter(scriptContext)->NormalizeLanguageTag(scriptContext, argString->GetSz(), &str);
  779. DelayLoadWindowsGlobalization *wsl = scriptContext->GetThreadContext()->GetWindowsGlobalizationLibrary();
  780. PCWSTR strBuf = wsl->WindowsGetStringRawBuffer(*str, NULL);
  781. retVal = Js::JavascriptString::NewCopySz(strBuf, scriptContext);
  782. if (FAILED(hr))
  783. {
  784. HandleOOMSOEHR(hr);
  785. //If we can't normalize the tag; return undefined.
  786. return scriptContext->GetLibrary()->GetUndefined();
  787. }
  788. return retVal;
  789. #endif
  790. }
  791. #ifdef INTL_ICU
  792. template <const char *(__cdecl *GetAvailableLocalesFunc)(int), int(__cdecl *CountAvailableLocalesFunc)(void)>
  793. static bool BinarySearchForLocale(const char *localeID)
  794. {
  795. const int count = CountAvailableLocalesFunc();
  796. int left = 0;
  797. int right = count - 1;
  798. int iterations = 0;
  799. while (true)
  800. {
  801. iterations += 1;
  802. if (left > right)
  803. {
  804. INTL_TRACE("Could not find localeID %S in %d iterations", localeID, iterations);
  805. return false;
  806. }
  807. int i = (left + right) / 2;
  808. Assert(i >= 0 && i < count);
  809. const char *cur = GetAvailableLocalesFunc(i);
  810. // Ensure that this list is actually binary searchable
  811. Assert(i > 0 ? strcmp(GetAvailableLocalesFunc(i - 1), cur) < 0 : true);
  812. Assert(i < count - 1 ? strcmp(GetAvailableLocalesFunc(i + 1), cur) > 0 : true);
  813. int res = strcmp(localeID, cur);
  814. if (res == 0)
  815. {
  816. INTL_TRACE("Found localeID %S in %d iterations", localeID, iterations);
  817. return true;
  818. }
  819. else if (res < 0)
  820. {
  821. right = i - 1;
  822. }
  823. else
  824. {
  825. left = i + 1;
  826. }
  827. }
  828. }
  829. template <const char *(__cdecl *GetAvailableLocalesFunc)(int), int(__cdecl *CountAvailableLocalesFunc)(void)>
  830. static bool IsLocaleAvailable(JavascriptString *langtag)
  831. {
  832. char localeID[ULOC_FULLNAME_CAPACITY] = { 0 };
  833. LangtagToLocaleID(langtag, localeID);
  834. if (!BinarySearchForLocale<GetAvailableLocalesFunc, CountAvailableLocalesFunc>(localeID))
  835. {
  836. // ICU's "available locales" do not include (all? most?) aliases.
  837. // For example, searching for "zh_TW" will return false, even though
  838. // zh_TW is equivalent to zh_Hant_TW, which would return true.
  839. // We can work around this by searching for both the locale as requested and
  840. // the locale in addition to all of its "likely subtags."
  841. // This works in practice because, for instance, unum_open("zh_TW") will actually
  842. // use "zh_Hant_TW" (confirmed with unum_getLocaleByType(..., ULOC_VALID_LOCALE))
  843. // The code below performs, for example, the following mappings:
  844. // pa_PK -> pa_Arab_PK
  845. // sr_RS -> sr_Cyrl_RS
  846. // zh_CN -> zh_Hans_CN
  847. // zh_TW -> zh_Hant_TW
  848. // TODO(jahorto): Determine if there is any scenario where a language tag + likely subtags is
  849. // not exactly functionally equivalent to the language tag on its own -- basically, where
  850. // constructor_open(language_tag) behaves differently to constructor_open(language_tag_and_likely_subtags)
  851. // for all supported constructors.
  852. UErrorCode status = U_ZERO_ERROR;
  853. char localeIDWithLikelySubtags[ULOC_FULLNAME_CAPACITY] = { 0 };
  854. int likelySubtagLen = uloc_addLikelySubtags(localeID, localeIDWithLikelySubtags, ULOC_FULLNAME_CAPACITY, &status);
  855. ICU_ASSERT(status, likelySubtagLen > 0 && likelySubtagLen < ULOC_FULLNAME_CAPACITY);
  856. return BinarySearchForLocale<GetAvailableLocalesFunc, CountAvailableLocalesFunc>(localeIDWithLikelySubtags);
  857. }
  858. return true;
  859. }
  860. #endif
  861. #ifdef INTL_ICU
  862. #define DEFINE_ISXLOCALEAVAILABLE(ctorShortName, icuNamespace) \
  863. Var IntlEngineInterfaceExtensionObject::EntryIntl_Is##ctorShortName##LocaleAvailable(RecyclableObject* function, CallInfo callInfo, ...) \
  864. { \
  865. EngineInterfaceObject_CommonFunctionProlog(function, callInfo); \
  866. INTL_CHECK_ARGS(args.Info.Count == 2 && JavascriptString::Is(args.Values[1])); \
  867. return scriptContext->GetLibrary()->GetTrueOrFalse( \
  868. IsLocaleAvailable<##icuNamespace##_getAvailable, ##icuNamespace##_countAvailable>(JavascriptString::UnsafeFromVar(args.Values[1])) \
  869. ); \
  870. }
  871. #else
  872. #define DEFINE_ISXLOCALEAVAILABLE(ctorShortName, icuNamespace) \
  873. Var IntlEngineInterfaceExtensionObject::EntryIntl_Is##ctorShortName##LocaleAvailable(RecyclableObject* function, CallInfo callInfo, ...) \
  874. { \
  875. AssertOrFailFastMsg(false, "Intl with Windows Globalization should never call Is" #ctorShortName "LocaleAvailable"); \
  876. return nullptr; \
  877. }
  878. #endif
  879. DEFINE_ISXLOCALEAVAILABLE(Collator, ucol)
  880. DEFINE_ISXLOCALEAVAILABLE(NF, unum)
  881. DEFINE_ISXLOCALEAVAILABLE(DTF, udat)
  882. // uplrules namespace doesn't have its own getAvailable/countAvailable
  883. // assume it supports whatever is supported in the base data
  884. DEFINE_ISXLOCALEAVAILABLE(PR, uloc)
  885. #ifdef INTL_ICU
  886. enum class LocaleDataKind
  887. {
  888. Collation,
  889. CaseFirst,
  890. Numeric,
  891. Calendar,
  892. NumberingSystem,
  893. HourCycle
  894. };
  895. #endif
  896. Var IntlEngineInterfaceExtensionObject::EntryIntl_GetLocaleData(RecyclableObject* function, CallInfo callInfo, ...)
  897. {
  898. #ifdef INTL_ICU
  899. EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
  900. INTL_CHECK_ARGS(
  901. args.Info.Count == 3 &&
  902. (JavascriptNumber::Is(args.Values[1]) || TaggedInt::Is(args.Values[1])) &&
  903. JavascriptString::Is(args.Values[2])
  904. );
  905. LocaleDataKind kind = (LocaleDataKind) (TaggedInt::Is(args.Values[1])
  906. ? TaggedInt::ToInt32(args.Values[1])
  907. : (int) JavascriptNumber::GetValue(args.Values[1]));
  908. JavascriptArray *ret = nullptr;
  909. UErrorCode status = U_ZERO_ERROR;
  910. char localeID[ULOC_FULLNAME_CAPACITY] = { 0 };
  911. JavascriptString *langtag = JavascriptString::UnsafeFromVar(args.Values[2]);
  912. LangtagToLocaleID(langtag, localeID);
  913. JavascriptLibrary *library = scriptContext->GetLibrary();
  914. PropertyOperationFlags flag = PropertyOperationFlags::PropertyOperation_None;
  915. if (kind == LocaleDataKind::Collation)
  916. {
  917. ScopedUEnumeration collations(ucol_getKeywordValuesForLocale("collation", localeID, false, &status));
  918. ICU_ASSERT(status, true);
  919. // the return array can't include "standard" and "search", but must have its first element be null (count - 2 + 1) [#sec-intl-collator-internal-slots]
  920. ret = library->CreateArray(uenum_count(collations, &status) - 1);
  921. ICU_ASSERT(status, true);
  922. ret->SetItem(0, library->GetNull(), flag);
  923. int collationLen = 0;
  924. const char *collation = nullptr;
  925. int i = 0;
  926. for (collation = uenum_next(collations, &collationLen, &status); collation != nullptr; collation = uenum_next(collations, &collationLen, &status))
  927. {
  928. ICU_ASSERT(status, collation != nullptr && collationLen > 0);
  929. if (strcmp(collation, "standard") == 0 || strcmp(collation, "search") == 0)
  930. {
  931. // continue does not create holes in ret because i is set outside the loop
  932. continue;
  933. }
  934. // OS#17172584: OOM during uloc_toUnicodeLocaleType can make this return nullptr even for known collations
  935. const char *unicodeCollation = ThrowOOMIfNull(uloc_toUnicodeLocaleType("collation", collation));
  936. const size_t unicodeCollationLen = strlen(unicodeCollation);
  937. // we only need strlen(unicodeCollation) + 1 char16s because unicodeCollation will always be ASCII (funnily enough)
  938. char16 *unicodeCollation16 = RecyclerNewArrayLeaf(scriptContext->GetRecycler(), char16, strlen(unicodeCollation) + 1);
  939. charcount_t unicodeCollation16Len = 0;
  940. HRESULT hr = utf8::NarrowStringToWideNoAlloc(
  941. unicodeCollation,
  942. unicodeCollationLen,
  943. unicodeCollation16,
  944. unicodeCollationLen + 1,
  945. &unicodeCollation16Len
  946. );
  947. AssertOrFailFastMsg(
  948. hr == S_OK && unicodeCollation16Len == unicodeCollationLen && unicodeCollation16Len < MaxCharCount,
  949. "Unicode collation char16 conversion was unsuccessful"
  950. );
  951. // i + 1 to not ovewrite leading null element
  952. ret->SetItem(i + 1, JavascriptString::NewWithBuffer(
  953. unicodeCollation16,
  954. unicodeCollation16Len,
  955. scriptContext
  956. ), PropertyOperationFlags::PropertyOperation_None);
  957. i++;
  958. }
  959. }
  960. else if (kind == LocaleDataKind::CaseFirst)
  961. {
  962. ScopedUCollator collator(ucol_open(localeID, &status));
  963. UColAttributeValue kf = ucol_getAttribute(collator, UCOL_CASE_FIRST, &status);
  964. ICU_ASSERT(status, true);
  965. ret = library->CreateArray(3);
  966. JavascriptString *falseStr = library->GetFalseDisplayString();
  967. JavascriptString *upperStr = library->GetIntlCaseFirstUpperString();
  968. JavascriptString *lowerStr = library->GetIntlCaseFirstLowerString();
  969. if (kf == UCOL_OFF)
  970. {
  971. ret->SetItem(0, falseStr, flag);
  972. ret->SetItem(1, upperStr, flag);
  973. ret->SetItem(2, lowerStr, flag);
  974. }
  975. else if (kf == UCOL_UPPER_FIRST)
  976. {
  977. ret->SetItem(0, upperStr, flag);
  978. ret->SetItem(1, lowerStr, flag);
  979. ret->SetItem(2, falseStr, flag);
  980. }
  981. else if (kf == UCOL_LOWER_FIRST)
  982. {
  983. ret->SetItem(0, lowerStr, flag);
  984. ret->SetItem(1, upperStr, flag);
  985. ret->SetItem(2, falseStr, flag);
  986. }
  987. }
  988. else if (kind == LocaleDataKind::Numeric)
  989. {
  990. ScopedUCollator collator(ucol_open(localeID, &status));
  991. UColAttributeValue kn = ucol_getAttribute(collator, UCOL_NUMERIC_COLLATION, &status);
  992. ICU_ASSERT(status, true);
  993. ret = library->CreateArray(2);
  994. JavascriptString *falseStr = library->GetFalseDisplayString();
  995. JavascriptString *trueStr = library->GetTrueDisplayString();
  996. if (kn == UCOL_OFF)
  997. {
  998. ret->SetItem(0, falseStr, flag);
  999. ret->SetItem(1, trueStr, flag);
  1000. }
  1001. else if (kn == UCOL_ON)
  1002. {
  1003. ret->SetItem(0, trueStr, flag);
  1004. ret->SetItem(1, falseStr, flag);
  1005. }
  1006. }
  1007. else if (kind == LocaleDataKind::Calendar)
  1008. {
  1009. ScopedUEnumeration calendars(ucal_getKeywordValuesForLocale("calendar", localeID, false, &status));
  1010. ret = library->CreateArray(uenum_count(calendars, &status));
  1011. ICU_ASSERT(status, true);
  1012. int calendarLen = 0;
  1013. const char *calendar = nullptr;
  1014. int i = 0;
  1015. for (calendar = uenum_next(calendars, &calendarLen, &status); calendar != nullptr; calendar = uenum_next(calendars, &calendarLen, &status))
  1016. {
  1017. ICU_ASSERT(status, calendar != nullptr && calendarLen > 0);
  1018. // OS#17172584: OOM during uloc_toUnicodeLocaleType can make this return nullptr even for known calendars
  1019. const char *unicodeCalendar = ThrowOOMIfNull(uloc_toUnicodeLocaleType("calendar", calendar));
  1020. const size_t unicodeCalendarLen = strlen(unicodeCalendar);
  1021. // we only need strlen(unicodeCalendar) + 1 char16s because unicodeCalendar will always be ASCII (funnily enough)
  1022. char16 *unicodeCalendar16 = RecyclerNewArrayLeaf(scriptContext->GetRecycler(), char16, strlen(unicodeCalendar) + 1);
  1023. charcount_t unicodeCalendar16Len = 0;
  1024. HRESULT hr = utf8::NarrowStringToWideNoAlloc(
  1025. unicodeCalendar,
  1026. unicodeCalendarLen,
  1027. unicodeCalendar16,
  1028. unicodeCalendarLen + 1,
  1029. &unicodeCalendar16Len
  1030. );
  1031. AssertOrFailFastMsg(
  1032. hr == S_OK && unicodeCalendar16Len == unicodeCalendarLen && unicodeCalendar16Len < MaxCharCount,
  1033. "Unicode calendar char16 conversion was unsuccessful"
  1034. );
  1035. ret->SetItem(i, JavascriptString::NewWithBuffer(
  1036. unicodeCalendar16,
  1037. static_cast<charcount_t>(unicodeCalendar16Len),
  1038. scriptContext
  1039. ), flag);
  1040. i++;
  1041. }
  1042. }
  1043. else if (kind == LocaleDataKind::NumberingSystem)
  1044. {
  1045. // unumsys_openAvailableNames has multiple bugs (http://bugs.icu-project.org/trac/ticket/11908) and also
  1046. // does not provide a locale-specific set of numbering systems
  1047. // the Intl spec provides a list of required numbering systems to support in #table-numbering-system-digits
  1048. // For now, assume that all of those numbering systems are supported, and just get the default using unumsys_open
  1049. // unumsys_open will also ensure that "native", "traditio", and "finance" are not returned, as per #sec-intl.datetimeformat-internal-slots
  1050. ScopedUNumberingSystem numsys(unumsys_open(localeID, &status));
  1051. ICU_ASSERT(status, true);
  1052. utf8::NarrowToWide numsysName(unumsys_getName(numsys));
  1053. // NOTE: update the initial array length if the list of available numbering systems changes in the future!
  1054. ret = library->CreateArray(22);
  1055. int i = 0;
  1056. ret->SetItem(i++, JavascriptString::NewCopySz(numsysName, scriptContext), flag);
  1057. // It doesn't matter that item 0 will be in the array twice (aside for size), because item 0 is the
  1058. // preferred numbering system for the given locale, so it has precedence over everything else
  1059. ret->SetItem(i++, library->GetIntlNumsysArabString(), flag);
  1060. ret->SetItem(i++, library->GetIntlNumsysArabextString(), flag);
  1061. ret->SetItem(i++, library->GetIntlNumsysBaliString(), flag);
  1062. ret->SetItem(i++, library->GetIntlNumsysBengString(), flag);
  1063. ret->SetItem(i++, library->GetIntlNumsysDevaString(), flag);
  1064. ret->SetItem(i++, library->GetIntlNumsysFullwideString(), flag);
  1065. ret->SetItem(i++, library->GetIntlNumsysGujrString(), flag);
  1066. ret->SetItem(i++, library->GetIntlNumsysGuruString(), flag);
  1067. ret->SetItem(i++, library->GetIntlNumsysHanidecString(), flag);
  1068. ret->SetItem(i++, library->GetIntlNumsysKhmrString(), flag);
  1069. ret->SetItem(i++, library->GetIntlNumsysKndaString(), flag);
  1070. ret->SetItem(i++, library->GetIntlNumsysLaooString(), flag);
  1071. ret->SetItem(i++, library->GetIntlNumsysLatnString(), flag);
  1072. ret->SetItem(i++, library->GetIntlNumsysLimbString(), flag);
  1073. ret->SetItem(i++, library->GetIntlNumsysMlymString(), flag);
  1074. ret->SetItem(i++, library->GetIntlNumsysMongString(), flag);
  1075. ret->SetItem(i++, library->GetIntlNumsysMymrString(), flag);
  1076. ret->SetItem(i++, library->GetIntlNumsysOryaString(), flag);
  1077. ret->SetItem(i++, library->GetIntlNumsysTamldecString(), flag);
  1078. ret->SetItem(i++, library->GetIntlNumsysTeluString(), flag);
  1079. ret->SetItem(i++, library->GetIntlNumsysThaiString(), flag);
  1080. ret->SetItem(i++, library->GetIntlNumsysTibtString(), flag);
  1081. }
  1082. else if (kind == LocaleDataKind::HourCycle)
  1083. {
  1084. // #sec-intl.datetimeformat-internal-slots: "[[LocaleData]][locale].hc must be < null, h11, h12, h23, h24 > for all locale values"
  1085. ret = library->CreateArray(5);
  1086. int i = 0;
  1087. ret->SetItem(i++, library->GetNull(), flag);
  1088. ret->SetItem(i++, library->GetIntlHourCycle11String(), flag);
  1089. ret->SetItem(i++, library->GetIntlHourCycle12String(), flag);
  1090. ret->SetItem(i++, library->GetIntlHourCycle23String(), flag);
  1091. ret->SetItem(i++, library->GetIntlHourCycle24String(), flag);
  1092. }
  1093. else
  1094. {
  1095. AssertOrFailFastMsg(false, "GetLocaleData called with unknown kind parameter");
  1096. }
  1097. return ret;
  1098. #else
  1099. AssertOrFailFastMsg(false, "Intl with Windows Globalization should never call GetLocaleData");
  1100. return nullptr;
  1101. #endif
  1102. }
  1103. Var IntlEngineInterfaceExtensionObject::EntryIntl_ResolveLocaleLookup(RecyclableObject* function, CallInfo callInfo, ...)
  1104. {
  1105. EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
  1106. if (args.Info.Count < 2 || !JavascriptString::Is(args.Values[1]))
  1107. {
  1108. // ResolveLocaleLookup of undefined or non-string is undefined
  1109. return scriptContext->GetLibrary()->GetUndefined();
  1110. }
  1111. #if defined(INTL_ICU)
  1112. #if defined(INTL_ICU_DEBUG)
  1113. Output::Print(_u("Intl::ResolveLocaleLookup returned false: EntryIntl_ResolveLocaleLookup returning null to fallback to JS\n"));
  1114. #endif
  1115. return scriptContext->GetLibrary()->GetNull();
  1116. #else
  1117. JavascriptString *argString = JavascriptString::FromVar(args.Values[1]);
  1118. PCWSTR passedLocale = argString->GetSz();
  1119. // REVIEW should we zero the whole array for safety?
  1120. WCHAR resolvedLocaleName[LOCALE_NAME_MAX_LENGTH];
  1121. resolvedLocaleName[0] = '\0';
  1122. ResolveLocaleName(passedLocale, resolvedLocaleName, _countof(resolvedLocaleName));
  1123. if (resolvedLocaleName[0] == '\0')
  1124. {
  1125. return scriptContext->GetLibrary()->GetUndefined();
  1126. }
  1127. return JavascriptString::NewCopySz(resolvedLocaleName, scriptContext);
  1128. #endif
  1129. }
  1130. Var IntlEngineInterfaceExtensionObject::EntryIntl_ResolveLocaleBestFit(RecyclableObject* function, CallInfo callInfo, ...)
  1131. {
  1132. EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
  1133. if (args.Info.Count < 2 || !JavascriptString::Is(args.Values[1]))
  1134. {
  1135. // NormalizeLanguageTag of undefined or non-string is undefined
  1136. return scriptContext->GetLibrary()->GetUndefined();
  1137. }
  1138. #if defined(INTL_ICU)
  1139. AssertOrFailFastMsg(false, "Intl-ICU does not implement ResolveLocaleBestFit");
  1140. return nullptr;
  1141. #else // !INTL_ICU
  1142. JavascriptString *localeStrings = JavascriptString::FromVar(args.Values[1]);
  1143. PCWSTR passedLocale = localeStrings->GetSz();
  1144. DelayLoadWindowsGlobalization* wgl = scriptContext->GetThreadContext()->GetWindowsGlobalizationLibrary();
  1145. WindowsGlobalizationAdapter* wga = GetWindowsGlobalizationAdapter(scriptContext);
  1146. AutoCOMPtr<DateTimeFormatting::IDateTimeFormatter> formatter;
  1147. HRESULT hr;
  1148. if (FAILED(hr = wga->CreateDateTimeFormatter(scriptContext, _u("longdate"), &passedLocale, 1, nullptr, nullptr, &formatter)))
  1149. {
  1150. HandleOOMSOEHR(hr);
  1151. return scriptContext->GetLibrary()->GetUndefined();
  1152. }
  1153. AutoHSTRING locale;
  1154. if (FAILED(hr = wga->GetResolvedLanguage(formatter, &locale)))
  1155. {
  1156. HandleOOMSOEHR(hr);
  1157. return scriptContext->GetLibrary()->GetUndefined();
  1158. }
  1159. return JavascriptString::NewCopySz(wgl->WindowsGetStringRawBuffer(*locale, NULL), scriptContext);
  1160. #endif
  1161. }
  1162. Var IntlEngineInterfaceExtensionObject::EntryIntl_GetDefaultLocale(RecyclableObject* function, CallInfo callInfo, ...)
  1163. {
  1164. EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
  1165. #ifdef INTL_WINGLOB
  1166. char16 defaultLocale[LOCALE_NAME_MAX_LENGTH];
  1167. defaultLocale[0] = '\0';
  1168. if (GetUserDefaultLocaleName(defaultLocale, _countof(defaultLocale)) == 0)
  1169. {
  1170. JavascriptError::MapAndThrowError(scriptContext, HRESULT_FROM_WIN32(GetLastError()));
  1171. }
  1172. return JavascriptString::NewCopySz(defaultLocale, scriptContext);
  1173. #else
  1174. UErrorCode status = U_ZERO_ERROR;
  1175. char defaultLangtag[ULOC_FULLNAME_CAPACITY] = { 0 };
  1176. char defaultLocaleID[ULOC_FULLNAME_CAPACITY] = { 0 };
  1177. int localeIDActual = uloc_getName(nullptr, defaultLocaleID, _countof(defaultLocaleID), &status);
  1178. ICU_ASSERT(status, localeIDActual > 0 && localeIDActual < _countof(defaultLocaleID));
  1179. int langtagActual = uloc_toLanguageTag(defaultLocaleID, defaultLangtag, _countof(defaultLangtag), true, &status);
  1180. ICU_ASSERT(status, langtagActual > 0 && langtagActual < _countof(defaultLangtag));
  1181. char16 *defaultLangtag16 = RecyclerNewArrayLeaf(scriptContext->GetRecycler(), char16, langtagActual + 1);
  1182. charcount_t defaultLangtag16Actual = 0;
  1183. utf8::NarrowStringToWideNoAlloc(defaultLangtag, static_cast<size_t>(langtagActual), defaultLangtag16, langtagActual + 1, &defaultLangtag16Actual);
  1184. AssertOrFailFastMsg(defaultLangtag16Actual == static_cast<size_t>(langtagActual), "Language tags should always be ASCII");
  1185. return JavascriptString::NewWithBuffer(defaultLangtag16, defaultLangtag16Actual, scriptContext);
  1186. #endif
  1187. }
  1188. Var IntlEngineInterfaceExtensionObject::EntryIntl_GetExtensions(RecyclableObject* function, CallInfo callInfo, ...)
  1189. {
  1190. EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
  1191. if (args.Info.Count < 2 || !JavascriptString::Is(args.Values[1]))
  1192. {
  1193. // NormalizeLanguageTag of undefined or non-string is undefined
  1194. return scriptContext->GetLibrary()->GetUndefined();
  1195. }
  1196. #ifdef INTL_WINGLOB
  1197. DelayLoadWindowsGlobalization* wgl = scriptContext->GetThreadContext()->GetWindowsGlobalizationLibrary();
  1198. WindowsGlobalizationAdapter* wga = GetWindowsGlobalizationAdapter(scriptContext);
  1199. AutoCOMPtr<ILanguage> language;
  1200. AutoCOMPtr<ILanguageExtensionSubtags> extensionSubtags;
  1201. HRESULT hr;
  1202. if (FAILED(hr = wga->CreateLanguage(scriptContext, JavascriptString::FromVar(args.Values[1])->GetSz(), &language)))
  1203. {
  1204. HandleOOMSOEHR(hr);
  1205. return scriptContext->GetLibrary()->GetUndefined();
  1206. }
  1207. if (FAILED(hr = language->QueryInterface(__uuidof(ILanguageExtensionSubtags), reinterpret_cast<void**>(&extensionSubtags))))
  1208. {
  1209. HandleOOMSOEHR(hr);
  1210. return scriptContext->GetLibrary()->GetUndefined();
  1211. }
  1212. Assert(extensionSubtags);
  1213. AutoHSTRING singletonString;
  1214. AutoCOMPtr<Windows::Foundation::Collections::IVectorView<HSTRING>> subtags;
  1215. uint32 length;
  1216. if (FAILED(hr = wgl->WindowsCreateString(_u("u"), 1, &singletonString)) || FAILED(hr = extensionSubtags->GetExtensionSubtags(*singletonString, &subtags)) || FAILED(subtags->get_Size(&length)))
  1217. {
  1218. HandleOOMSOEHR(hr);
  1219. return scriptContext->GetLibrary()->GetUndefined();
  1220. }
  1221. JavascriptArray *toReturn = scriptContext->GetLibrary()->CreateArray(length);
  1222. for (uint32 i = 0; i < length; i++)
  1223. {
  1224. AutoHSTRING str;
  1225. if (!FAILED(hr = wga->GetItemAt(subtags, i, &str)))
  1226. {
  1227. toReturn->SetItem(i, JavascriptString::NewCopySz(wgl->WindowsGetStringRawBuffer(*str, NULL), scriptContext), Js::PropertyOperationFlags::PropertyOperation_None);
  1228. }
  1229. else
  1230. {
  1231. HandleOOMSOEHR(hr);
  1232. }
  1233. }
  1234. return toReturn;
  1235. #else
  1236. AssertOrFailFastMsg(false, "ICU should not be calling platform.getExtensions");
  1237. return nullptr;
  1238. #endif
  1239. }
  1240. #ifdef INTL_ICU
  1241. // This is used by both NumberFormat and PluralRules
  1242. static void SetUNumberFormatDigitOptions(UNumberFormat *fmt, DynamicObject *state)
  1243. {
  1244. if (JavascriptOperators::HasProperty(state, PropertyIds::minimumSignificantDigits))
  1245. {
  1246. unum_setAttribute(fmt, UNUM_SIGNIFICANT_DIGITS_USED, true);
  1247. unum_setAttribute(fmt, UNUM_MIN_SIGNIFICANT_DIGITS, AssertIntegerProperty(state, PropertyIds::minimumSignificantDigits));
  1248. unum_setAttribute(fmt, UNUM_MAX_SIGNIFICANT_DIGITS, AssertIntegerProperty(state, PropertyIds::maximumSignificantDigits));
  1249. }
  1250. else
  1251. {
  1252. unum_setAttribute(fmt, UNUM_MIN_INTEGER_DIGITS, AssertIntegerProperty(state, PropertyIds::minimumIntegerDigits));
  1253. unum_setAttribute(fmt, UNUM_MIN_FRACTION_DIGITS, AssertIntegerProperty(state, PropertyIds::minimumFractionDigits));
  1254. unum_setAttribute(fmt, UNUM_MAX_FRACTION_DIGITS, AssertIntegerProperty(state, PropertyIds::maximumFractionDigits));
  1255. }
  1256. }
  1257. #endif
  1258. Var IntlEngineInterfaceExtensionObject::EntryIntl_CacheNumberFormat(RecyclableObject * function, CallInfo callInfo, ...)
  1259. {
  1260. EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
  1261. INTL_CHECK_ARGS(args.Info.Count == 2 && DynamicObject::Is(args.Values[1]));
  1262. #if defined(INTL_ICU)
  1263. DynamicObject *state = DynamicObject::UnsafeFromVar(args.Values[1]);
  1264. // always AssertOrFailFast that the properties we need are there, because if they aren't, Intl.js isn't functioning correctly
  1265. NumberFormatStyle style = AssertEnumProperty<NumberFormatStyle>(state, PropertyIds::formatterToUse);
  1266. UNumberFormatStyle unumStyle = UNUM_IGNORE;
  1267. UErrorCode status = U_ZERO_ERROR;
  1268. JavascriptString *currency = nullptr;
  1269. JavascriptString *langtag = AssertStringProperty(state, PropertyIds::locale);
  1270. char localeID[ULOC_FULLNAME_CAPACITY] = { 0 };
  1271. LangtagToLocaleID(langtag, localeID);
  1272. if (style == NumberFormatStyle::Decimal)
  1273. {
  1274. unumStyle = UNUM_DECIMAL;
  1275. }
  1276. else if (style == NumberFormatStyle::Percent)
  1277. {
  1278. unumStyle = UNUM_PERCENT;
  1279. }
  1280. else if (style == NumberFormatStyle::Currency)
  1281. {
  1282. NumberFormatCurrencyDisplay nfcd = AssertEnumProperty<NumberFormatCurrencyDisplay>(state, PropertyIds::currencyDisplayToUse);
  1283. // TODO(jahorto): Investigate making our enum values equal to the corresponding UNumberFormatStyle values
  1284. if (nfcd == NumberFormatCurrencyDisplay::Symbol)
  1285. {
  1286. unumStyle = UNUM_CURRENCY;
  1287. }
  1288. else if (nfcd == NumberFormatCurrencyDisplay::Code)
  1289. {
  1290. unumStyle = UNUM_CURRENCY_ISO;
  1291. }
  1292. else if (nfcd == NumberFormatCurrencyDisplay::Name)
  1293. {
  1294. unumStyle = UNUM_CURRENCY_PLURAL;
  1295. }
  1296. currency = AssertStringProperty(state, PropertyIds::currency);
  1297. }
  1298. AssertOrFailFast(unumStyle != UNUM_IGNORE);
  1299. auto fmt = FinalizableUNumberFormat::New(scriptContext->GetRecycler(), unum_open(unumStyle, nullptr, 0, localeID, nullptr, &status));
  1300. ICU_ASSERT(status, true);
  1301. bool groupingUsed = AssertBooleanProperty(state, PropertyIds::useGrouping);
  1302. unum_setAttribute(*fmt, UNUM_GROUPING_USED, groupingUsed);
  1303. unum_setAttribute(*fmt, UNUM_ROUNDING_MODE, UNUM_ROUND_HALFUP);
  1304. SetUNumberFormatDigitOptions(*fmt, state);
  1305. if (currency != nullptr)
  1306. {
  1307. unum_setTextAttribute(*fmt, UNUM_CURRENCY_CODE, reinterpret_cast<const UChar *>(currency->GetSz()), currency->GetLength(), &status);
  1308. ICU_ASSERT(status, true);
  1309. }
  1310. state->SetInternalProperty(
  1311. InternalPropertyIds::CachedUNumberFormat,
  1312. fmt,
  1313. PropertyOperationFlags::PropertyOperation_None,
  1314. nullptr
  1315. );
  1316. return scriptContext->GetLibrary()->GetUndefined();
  1317. #else
  1318. HRESULT hr = S_OK;
  1319. JavascriptString *localeJSstr = nullptr;
  1320. DynamicObject *options = DynamicObject::FromVar(args.Values[1]);
  1321. DelayLoadWindowsGlobalization* wgl = scriptContext->GetThreadContext()->GetWindowsGlobalizationLibrary();
  1322. WindowsGlobalizationAdapter* wga = GetWindowsGlobalizationAdapter(scriptContext);
  1323. Var propertyValue;
  1324. // Verify locale is present
  1325. // REVIEW (doilij): Fix comparison of the unsigned value <= 0
  1326. if (!GetTypedPropertyBuiltInFrom(options, __locale, JavascriptString) || (localeJSstr = JavascriptString::FromVar(propertyValue))->GetLength() <= 0)
  1327. {
  1328. // REVIEW (doilij): Should we throw? Or otherwise, from Intl.js, should detect something didn't work right here...
  1329. return scriptContext->GetLibrary()->GetUndefined();
  1330. }
  1331. //First we have to determine which formatter(number, percent, or currency) we will be using.
  1332. //Note some options might not be present.
  1333. AutoCOMPtr<NumberFormatting::INumberFormatter> numberFormatter(nullptr);
  1334. PCWSTR locale = localeJSstr->GetSz();
  1335. uint16 formatterToUseVal = 0; // 0 (default) is number, 1 is percent, 2 is currency
  1336. if (GetTypedPropertyBuiltInFrom(options, __formatterToUse, TaggedInt) && (formatterToUseVal = TaggedInt::ToUInt16(propertyValue)) == 1)
  1337. {
  1338. //Use the percent formatter
  1339. IfFailThrowHr(wga->CreatePercentFormatter(scriptContext, &locale, 1, &numberFormatter));
  1340. }
  1341. else if (formatterToUseVal == 2)
  1342. {
  1343. //Use the currency formatter
  1344. AutoCOMPtr<NumberFormatting::ICurrencyFormatter> currencyFormatter(nullptr);
  1345. if (!GetTypedPropertyBuiltInFrom(options, __currency, JavascriptString))
  1346. {
  1347. return scriptContext->GetLibrary()->GetUndefined();
  1348. }
  1349. //API call retrieves a currency formatter, have to query its interface for numberFormatter
  1350. IfFailThrowHr(GetWindowsGlobalizationAdapter(scriptContext)->CreateCurrencyFormatter(scriptContext, &locale, 1, JavascriptString::FromVar(propertyValue)->GetSz(), &currencyFormatter));
  1351. if (GetTypedPropertyBuiltInFrom(options, __currencyDisplayToUse, TaggedInt)) // 0 is for symbol, 1 is for code, 2 is for name.
  1352. //Currently name isn't supported; so it will default to code in that case.
  1353. {
  1354. AutoCOMPtr<NumberFormatting::ICurrencyFormatter2> currencyFormatter2(nullptr);
  1355. IfFailThrowHr(currencyFormatter->QueryInterface(__uuidof(NumberFormatting::ICurrencyFormatter2), reinterpret_cast<void**>(&currencyFormatter2)));
  1356. if (TaggedInt::ToUInt16(propertyValue) == 0)
  1357. {
  1358. IfFailThrowHr(currencyFormatter2->put_Mode(NumberFormatting::CurrencyFormatterMode::CurrencyFormatterMode_UseSymbol));
  1359. }
  1360. else
  1361. {
  1362. IfFailThrowHr(currencyFormatter2->put_Mode(NumberFormatting::CurrencyFormatterMode::CurrencyFormatterMode_UseCurrencyCode));
  1363. }
  1364. }
  1365. IfFailThrowHr(currencyFormatter->QueryInterface(__uuidof(NumberFormatting::INumberFormatter), reinterpret_cast<void**>(&numberFormatter)));
  1366. }
  1367. else
  1368. {
  1369. //Use the number formatter (default)
  1370. IfFailThrowHr(wga->CreateNumberFormatter(scriptContext, &locale, 1, &numberFormatter));
  1371. }
  1372. Assert(numberFormatter);
  1373. AutoCOMPtr<NumberFormatting::ISignedZeroOption> signedZeroOption(nullptr);
  1374. IfFailThrowHr(numberFormatter->QueryInterface(__uuidof(NumberFormatting::ISignedZeroOption), reinterpret_cast<void**>(&signedZeroOption)));
  1375. IfFailThrowHr(signedZeroOption->put_IsZeroSigned(true));
  1376. //Configure non-digit related options
  1377. AutoCOMPtr<NumberFormatting::INumberFormatterOptions> numberFormatterOptions(nullptr);
  1378. IfFailThrowHr(numberFormatter->QueryInterface(__uuidof(NumberFormatting::INumberFormatterOptions), reinterpret_cast<void**>(&numberFormatterOptions)));
  1379. Assert(numberFormatterOptions);
  1380. if (GetTypedPropertyBuiltInFrom(options, __useGrouping, JavascriptBoolean))
  1381. {
  1382. IfFailThrowHr(numberFormatterOptions->put_IsGrouped((boolean)(JavascriptBoolean::FromVar(propertyValue)->GetValue())));
  1383. }
  1384. //Get the numeral system and add it to the object since it will be located in the locale
  1385. AutoHSTRING hNumeralSystem;
  1386. AutoHSTRING hResolvedLanguage;
  1387. uint32 length;
  1388. IfFailThrowHr(wga->GetNumeralSystem(numberFormatterOptions, &hNumeralSystem));
  1389. SetHSTRINGPropertyBuiltInOn(options, __numberingSystem, *hNumeralSystem);
  1390. IfFailThrowHr(wga->GetResolvedLanguage(numberFormatterOptions, &hResolvedLanguage));
  1391. SetHSTRINGPropertyBuiltInOn(options, __locale, *hResolvedLanguage);
  1392. AutoCOMPtr<NumberFormatting::INumberRounderOption> rounderOptions(nullptr);
  1393. IfFailThrowHr(numberFormatter->QueryInterface(__uuidof(NumberFormatting::INumberRounderOption), reinterpret_cast<void**>(&rounderOptions)));
  1394. Assert(rounderOptions);
  1395. if (HasPropertyBuiltInOn(options, __minimumSignificantDigits) || HasPropertyBuiltInOn(options, __maximumSignificantDigits))
  1396. {
  1397. uint16 minSignificantDigits = 1, maxSignificantDigits = 21;
  1398. //Do significant digit rounding
  1399. if (GetTypedPropertyBuiltInFrom(options, __minimumSignificantDigits, TaggedInt))
  1400. {
  1401. minSignificantDigits = max<uint16>(min<uint16>(TaggedInt::ToUInt16(propertyValue), 21), 1);
  1402. }
  1403. if (GetTypedPropertyBuiltInFrom(options, __maximumSignificantDigits, TaggedInt))
  1404. {
  1405. maxSignificantDigits = max<uint16>(min<uint16>(TaggedInt::ToUInt16(propertyValue), 21), minSignificantDigits);
  1406. }
  1407. prepareWithSignificantDigits(scriptContext, rounderOptions, numberFormatter, numberFormatterOptions, minSignificantDigits, maxSignificantDigits);
  1408. }
  1409. else
  1410. {
  1411. uint16 minFractionDigits = 0, maxFractionDigits = 3, minIntegerDigits = 1;
  1412. //Do fraction/integer digit rounding
  1413. if (GetTypedPropertyBuiltInFrom(options, __minimumIntegerDigits, TaggedInt))
  1414. {
  1415. minIntegerDigits = max<uint16>(min<uint16>(TaggedInt::ToUInt16(propertyValue), 21), 1);
  1416. }
  1417. if (GetTypedPropertyBuiltInFrom(options, __minimumFractionDigits, TaggedInt))
  1418. {
  1419. minFractionDigits = min<uint16>(TaggedInt::ToUInt16(propertyValue), 20);//ToUInt16 will get rid of negatives by making them high
  1420. }
  1421. if (GetTypedPropertyBuiltInFrom(options, __maximumFractionDigits, TaggedInt))
  1422. {
  1423. maxFractionDigits = max(min<uint16>(TaggedInt::ToUInt16(propertyValue), 20), minFractionDigits);//ToUInt16 will get rid of negatives by making them high
  1424. }
  1425. prepareWithFractionIntegerDigits(scriptContext, rounderOptions, numberFormatterOptions, minFractionDigits, maxFractionDigits + (formatterToUseVal == 1 ? 2 : 0), minIntegerDigits);//extend max fractions for percent
  1426. }
  1427. //Set the object as a cache
  1428. numberFormatter->AddRef();
  1429. options->SetInternalProperty(Js::InternalPropertyIds::HiddenObject, AutoCOMJSObject::New(scriptContext->GetRecycler(), numberFormatter), Js::PropertyOperationFlags::PropertyOperation_None, NULL);
  1430. return scriptContext->GetLibrary()->GetUndefined();
  1431. #endif
  1432. }
  1433. // Unlike CacheNumberFormat; this call takes an additional parameter to specify whether we are going to cache it.
  1434. // We have to create this formatter twice; first time get the date/time patterns; and second time cache with correct format string.
  1435. Var IntlEngineInterfaceExtensionObject::EntryIntl_CreateDateTimeFormat(RecyclableObject * function, CallInfo callInfo, ...)
  1436. {
  1437. EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
  1438. if (args.Info.Count < 3 || !DynamicObject::Is(args.Values[1]) || !JavascriptBoolean::Is(args.Values[2]))
  1439. {
  1440. return scriptContext->GetLibrary()->GetUndefined();
  1441. }
  1442. #ifdef INTL_WINGLOB
  1443. DynamicObject* obj = DynamicObject::FromVar(args.Values[1]);
  1444. DelayLoadWindowsGlobalization* wgl = scriptContext->GetThreadContext()->GetWindowsGlobalizationLibrary();
  1445. WindowsGlobalizationAdapter* wga = GetWindowsGlobalizationAdapter(scriptContext);
  1446. HRESULT hr;
  1447. Var propertyValue = nullptr;
  1448. uint32 length;
  1449. PCWSTR locale = GetTypedPropertyBuiltInFrom(obj, __locale, JavascriptString) ? JavascriptString::FromVar(propertyValue)->GetSz() : nullptr;
  1450. PCWSTR templateString = GetTypedPropertyBuiltInFrom(obj, __templateString, JavascriptString) ? JavascriptString::FromVar(propertyValue)->GetSz() : nullptr;
  1451. if (locale == nullptr || templateString == nullptr)
  1452. {
  1453. AssertMsg(false, "For some reason, locale and templateString aren't defined or aren't a JavascriptString.");
  1454. return scriptContext->GetLibrary()->GetUndefined();
  1455. }
  1456. PCWSTR clock = GetTypedPropertyBuiltInFrom(obj, __windowsClock, JavascriptString) ? JavascriptString::FromVar(propertyValue)->GetSz() : nullptr;
  1457. AutoHSTRING hDummyCalendar;
  1458. if (clock != nullptr)
  1459. {
  1460. //Because both calendar and clock are needed to pass into the datetimeformatter constructor (or neither); create a dummy one to get the value of calendar out so clock can be passed in with it.
  1461. AutoCOMPtr<DateTimeFormatting::IDateTimeFormatter> dummyFormatter;
  1462. IfFailThrowHr(wga->CreateDateTimeFormatter(scriptContext, templateString, &locale, 1, nullptr, nullptr, &dummyFormatter));
  1463. IfFailThrowHr(wga->GetCalendar(dummyFormatter, &hDummyCalendar));
  1464. }
  1465. //Now create the real formatter.
  1466. AutoCOMPtr<DateTimeFormatting::IDateTimeFormatter> cachedFormatter;
  1467. IfFailThrowHr(wga->CreateDateTimeFormatter(scriptContext, templateString, &locale, 1,
  1468. clock == nullptr ? nullptr : wgl->WindowsGetStringRawBuffer(*hDummyCalendar, &length), clock, &cachedFormatter));
  1469. AutoHSTRING hCalendar;
  1470. AutoHSTRING hClock;
  1471. AutoHSTRING hLocale;
  1472. AutoHSTRING hNumberingSystem;
  1473. //In case the upper code path wasn't hit; extract the calendar string again so it can be set.
  1474. IfFailThrowHr(wga->GetCalendar(cachedFormatter, &hCalendar));
  1475. SetHSTRINGPropertyBuiltInOn(obj, __windowsCalendar, *hCalendar);
  1476. IfFailThrowHr(wga->GetClock(cachedFormatter, &hClock));
  1477. SetHSTRINGPropertyBuiltInOn(obj, __windowsClock, *hClock);
  1478. IfFailThrowHr(wga->GetResolvedLanguage(cachedFormatter, &hLocale));
  1479. SetHSTRINGPropertyBuiltInOn(obj, __locale, *hLocale);
  1480. //Get the numbering system
  1481. IfFailThrowHr(wga->GetNumeralSystem(cachedFormatter, &hNumberingSystem));
  1482. SetHSTRINGPropertyBuiltInOn(obj, __numberingSystem, *hNumberingSystem);
  1483. //Extract the pattern strings
  1484. AutoCOMPtr<Windows::Foundation::Collections::IVectorView<HSTRING>> dateResult;
  1485. IfFailThrowHr(cachedFormatter->get_Patterns(&dateResult));
  1486. IfFailThrowHr(dateResult->get_Size(&length));
  1487. JavascriptArray *patternStrings = scriptContext->GetLibrary()->CreateArray(length);
  1488. for (uint32 i = 0; i < length; i++)
  1489. {
  1490. AutoHSTRING item;
  1491. IfFailThrowHr(wga->GetItemAt(dateResult, i, &item));
  1492. patternStrings->SetItem(i, Js::JavascriptString::NewCopySz(wgl->WindowsGetStringRawBuffer(*item, NULL), scriptContext), PropertyOperation_None);
  1493. }
  1494. SetPropertyBuiltInOn(obj, __patternStrings, patternStrings);
  1495. //This parameter tells us whether we are caching it this time around; or just validating pattern strings
  1496. if ((boolean)(JavascriptBoolean::FromVar(args.Values[2])->GetValue()))
  1497. {
  1498. //If timeZone is undefined; then use the standard dateTimeFormatter to format in local time; otherwise use the IDateTimeFormatter2 to format using specified timezone (UTC)
  1499. if (!GetPropertyBuiltInFrom(obj, __timeZone) || JavascriptOperators::IsUndefinedObject(propertyValue))
  1500. {
  1501. cachedFormatter->AddRef();
  1502. obj->SetInternalProperty(Js::InternalPropertyIds::HiddenObject, AutoCOMJSObject::New(scriptContext->GetRecycler(), cachedFormatter), Js::PropertyOperationFlags::PropertyOperation_None, NULL);
  1503. }
  1504. else
  1505. {
  1506. AutoCOMPtr<DateTimeFormatting::IDateTimeFormatter2> tzCachedFormatter;
  1507. IfFailThrowHr(cachedFormatter->QueryInterface(__uuidof(DateTimeFormatting::IDateTimeFormatter2), reinterpret_cast<void**>(&tzCachedFormatter)));
  1508. tzCachedFormatter->AddRef();
  1509. //Set the object as a cache
  1510. obj->SetInternalProperty(Js::InternalPropertyIds::HiddenObject, AutoCOMJSObject::New(scriptContext->GetRecycler(), tzCachedFormatter), Js::PropertyOperationFlags::PropertyOperation_None, NULL);
  1511. }
  1512. }
  1513. return scriptContext->GetLibrary()->GetUndefined();
  1514. #else
  1515. // TODO (doilij): implement INTL_ICU version
  1516. #ifdef INTL_ICU_DEBUG
  1517. Output::Print(_u("EntryIntl_CreateDateTimeFormat > returning null, fallback to JS\n"));
  1518. #endif
  1519. return scriptContext->GetLibrary()->GetNull();
  1520. #endif
  1521. }
  1522. Var IntlEngineInterfaceExtensionObject::EntryIntl_LocaleCompare(RecyclableObject* function, CallInfo callInfo, ...)
  1523. {
  1524. #ifdef INTL_WINGLOB
  1525. AssertOrFailFastMsg(false, "platform.localeCompare should not be called in Intl-WinGlob");
  1526. return nullptr;
  1527. #else
  1528. EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
  1529. INTL_CHECK_ARGS(
  1530. args.Info.Count == 5 &&
  1531. JavascriptString::Is(args[1]) &&
  1532. JavascriptString::Is(args[2]) &&
  1533. DynamicObject::Is(args[3]) &&
  1534. JavascriptBoolean::Is(args[4])
  1535. );
  1536. JavascriptString *left = JavascriptString::UnsafeFromVar(args[1]);
  1537. JavascriptString *right = JavascriptString::UnsafeFromVar(args[2]);
  1538. DynamicObject *state = DynamicObject::UnsafeFromVar(args[3]);
  1539. bool forStringPrototypeLocaleCompare = JavascriptBoolean::UnsafeFromVar(args[4])->GetValue();
  1540. if (forStringPrototypeLocaleCompare)
  1541. {
  1542. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(String_Prototype_localeCompare);
  1543. INTL_TRACE("Calling '%s'.localeCompare('%s', ...)", left->GetSz(), right->GetSz());
  1544. }
  1545. else
  1546. {
  1547. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Collator_Prototype_compare);
  1548. INTL_TRACE("Calling Collator.prototype.compare('%s', '%s')", left->GetSz(), right->GetSz());
  1549. }
  1550. // Below, we lazy-initialize the backing UCollator on the first call to localeCompare
  1551. // On subsequent calls, the UCollator will be cached in state.CachedUCollator
  1552. Var cachedUCollator = nullptr;
  1553. FinalizableUCollator *coll = nullptr;
  1554. UErrorCode status = U_ZERO_ERROR;
  1555. if (state->GetInternalProperty(state, InternalPropertyIds::CachedUCollator, &cachedUCollator, nullptr, scriptContext))
  1556. {
  1557. coll = reinterpret_cast<FinalizableUCollator *>(cachedUCollator);
  1558. INTL_TRACE("Using previously cached UCollator (0x%x)", coll);
  1559. }
  1560. else
  1561. {
  1562. // the object key is locale according to Intl spec, but its more accurately a BCP47 Language Tag, not an ICU LocaleID
  1563. JavascriptString *langtag = AssertStringProperty(state, PropertyIds::locale);
  1564. CollatorSensitivity sensitivity = AssertEnumProperty<CollatorSensitivity>(state, PropertyIds::sensitivityEnum);
  1565. bool ignorePunctuation = AssertBooleanProperty(state, PropertyIds::ignorePunctuation);
  1566. bool numeric = AssertBooleanProperty(state, PropertyIds::numeric);
  1567. CollatorCaseFirst caseFirst = AssertEnumProperty<CollatorCaseFirst>(state, PropertyIds::caseFirstEnum);
  1568. char localeID[ULOC_FULLNAME_CAPACITY] = { 0 };
  1569. LangtagToLocaleID(langtag, localeID);
  1570. coll = FinalizableUCollator::New(scriptContext->GetRecycler(), ucol_open(localeID, &status));
  1571. ICU_ASSERT(status, true);
  1572. // REVIEW(jahorto): Anything that requires a status will no-op if its in a failure state
  1573. // Thus, we can ICU_ASSERT the status once after all of the properties are set for simplicity
  1574. if (sensitivity == CollatorSensitivity::Base)
  1575. {
  1576. ucol_setStrength(*coll, UCOL_PRIMARY);
  1577. }
  1578. else if (sensitivity == CollatorSensitivity::Accent)
  1579. {
  1580. ucol_setStrength(*coll, UCOL_SECONDARY);
  1581. }
  1582. else if (sensitivity == CollatorSensitivity::Case)
  1583. {
  1584. // see "description" for the caseLevel default option: http://userguide.icu-project.org/collation/customization
  1585. ucol_setStrength(*coll, UCOL_PRIMARY);
  1586. ucol_setAttribute(*coll, UCOL_CASE_LEVEL, UCOL_ON, &status);
  1587. }
  1588. else if (sensitivity == CollatorSensitivity::Variant)
  1589. {
  1590. ucol_setStrength(*coll, UCOL_TERTIARY);
  1591. }
  1592. if (ignorePunctuation)
  1593. {
  1594. // see http://userguide.icu-project.org/collation/customization/ignorepunct
  1595. ucol_setAttribute(*coll, UCOL_ALTERNATE_HANDLING, UCOL_SHIFTED, &status);
  1596. }
  1597. if (numeric)
  1598. {
  1599. ucol_setAttribute(*coll, UCOL_NUMERIC_COLLATION, UCOL_ON, &status);
  1600. }
  1601. if (caseFirst == CollatorCaseFirst::Upper)
  1602. {
  1603. ucol_setAttribute(*coll, UCOL_CASE_FIRST, UCOL_UPPER_FIRST, &status);
  1604. }
  1605. else if (caseFirst == CollatorCaseFirst::Lower)
  1606. {
  1607. ucol_setAttribute(*coll, UCOL_CASE_FIRST, UCOL_LOWER_FIRST, &status);
  1608. }
  1609. // Ensure that collator configuration was successfull
  1610. ICU_ASSERT(status, true);
  1611. INTL_TRACE(
  1612. "Caching UCollator (0x%x) with langtag = %s, sensitivity = %d, caseFirst = %d, ignorePunctuation = %d, and numeric = %d",
  1613. coll,
  1614. langtag->GetSz(),
  1615. sensitivity,
  1616. caseFirst,
  1617. ignorePunctuation,
  1618. numeric
  1619. );
  1620. // cache coll for later use (so that the condition that brought us here returns true for future calls)
  1621. state->SetInternalProperty(
  1622. InternalPropertyIds::CachedUCollator,
  1623. coll,
  1624. PropertyOperationFlags::PropertyOperation_None,
  1625. nullptr
  1626. );
  1627. }
  1628. // As of ES2015, String.prototype.localeCompare must compare canonically equivalent strings as equal
  1629. BEGIN_TEMP_ALLOCATOR(tempAllocator, scriptContext, _u("EntryIntl_LocaleCompare"));
  1630. const char16 *leftNormalized = nullptr;
  1631. charcount_t leftNormalizedLength = 0;
  1632. if (UnicodeText::IsNormalizedString(UnicodeText::NormalizationForm::C, left->GetSz(), left->GetLength()))
  1633. {
  1634. leftNormalized = left->GetSz();
  1635. leftNormalizedLength = left ->GetLength();
  1636. }
  1637. else
  1638. {
  1639. leftNormalized = left->GetNormalizedString(UnicodeText::NormalizationForm::C, tempAllocator, leftNormalizedLength);
  1640. }
  1641. const char16 *rightNormalized = nullptr;
  1642. charcount_t rightNormalizedLength = 0;
  1643. if (UnicodeText::IsNormalizedString(UnicodeText::NormalizationForm::C, right->GetSz(), right->GetLength()))
  1644. {
  1645. rightNormalized = right->GetSz();
  1646. rightNormalizedLength = right->GetLength();
  1647. }
  1648. else
  1649. {
  1650. rightNormalized = right->GetNormalizedString(UnicodeText::NormalizationForm::C, tempAllocator, rightNormalizedLength);
  1651. }
  1652. static_assert(UCOL_LESS == -1 && UCOL_EQUAL == 0 && UCOL_GREATER == 1, "ucol_strcoll should return values compatible with localeCompare");
  1653. Var ret = JavascriptNumber::ToVar(ucol_strcoll(
  1654. *coll,
  1655. reinterpret_cast<const UChar *>(leftNormalized),
  1656. leftNormalizedLength,
  1657. reinterpret_cast<const UChar *>(rightNormalized),
  1658. rightNormalizedLength
  1659. ), scriptContext);
  1660. END_TEMP_ALLOCATOR(tempAllocator, scriptContext);
  1661. return ret;
  1662. #endif
  1663. }
  1664. #ifdef INTL_WINGLOB
  1665. static DWORD GetCompareStringComparisonFlags(CollatorSensitivity sensitivity, bool ignorePunctuation, bool numeric)
  1666. {
  1667. DWORD flags = 0;
  1668. if (sensitivity == CollatorSensitivity::Base)
  1669. {
  1670. flags |= LINGUISTIC_IGNOREDIACRITIC | LINGUISTIC_IGNORECASE | NORM_IGNOREKANATYPE | NORM_IGNOREWIDTH;
  1671. }
  1672. else if (sensitivity == CollatorSensitivity::Accent)
  1673. {
  1674. flags |= LINGUISTIC_IGNORECASE | NORM_IGNOREKANATYPE | NORM_IGNOREWIDTH;
  1675. }
  1676. else if (sensitivity == CollatorSensitivity::Case)
  1677. {
  1678. flags |= NORM_IGNOREKANATYPE | NORM_IGNOREWIDTH | LINGUISTIC_IGNOREDIACRITIC;
  1679. }
  1680. else if (sensitivity == CollatorSensitivity::Variant)
  1681. {
  1682. flags |= NORM_LINGUISTIC_CASING;
  1683. }
  1684. if (ignorePunctuation)
  1685. {
  1686. flags |= NORM_IGNORESYMBOLS;
  1687. }
  1688. if (numeric)
  1689. {
  1690. flags |= SORT_DIGITSASNUMBERS;
  1691. }
  1692. return flags;
  1693. }
  1694. #endif
  1695. Var IntlEngineInterfaceExtensionObject::EntryIntl_CompareString(RecyclableObject* function, CallInfo callInfo, ...)
  1696. {
  1697. #ifdef INTL_ICU
  1698. AssertOrFailFastMsg(false, "EntryIntl_CompareString should not be called in Intl-ICU");
  1699. return nullptr;
  1700. #else
  1701. EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
  1702. INTL_CHECK_ARGS(args.Info.Count >= 3 && JavascriptString::Is(args[1]) && JavascriptString::Is(args[2]));
  1703. const char16 *locale = nullptr; // args[3]
  1704. char16 defaultLocale[LOCALE_NAME_MAX_LENGTH] = { 0 };
  1705. CollatorSensitivity sensitivity = CollatorSensitivity::Default; // args[4]
  1706. bool ignorePunctuation = false; // args[5]
  1707. bool numeric = false; // args[6]
  1708. JavascriptString *str1 = JavascriptString::FromVar(args.Values[1]);
  1709. JavascriptString *str2 = JavascriptString::FromVar(args.Values[2]);
  1710. CollatorCaseFirst caseFirst = CollatorCaseFirst::Default; // args[7]
  1711. // we only need to parse arguments 3 through 7 if locale and options are provided
  1712. // see fast path in JavascriptString::EntryLocaleCompare
  1713. if (args.Info.Count > 3)
  1714. {
  1715. if (args.Info.Count < 8)
  1716. {
  1717. JavascriptError::MapAndThrowError(scriptContext, E_INVALIDARG);
  1718. }
  1719. if (!JavascriptOperators::IsUndefinedObject(args.Values[3]) && JavascriptString::Is(args.Values[3]))
  1720. {
  1721. locale = JavascriptString::FromVar(args.Values[3])->GetSz();
  1722. }
  1723. else
  1724. {
  1725. JavascriptError::MapAndThrowError(scriptContext, E_INVALIDARG);
  1726. }
  1727. if (!JavascriptOperators::IsUndefinedObject(args.Values[4]) && TaggedInt::Is(args.Values[4]))
  1728. {
  1729. sensitivity = static_cast<CollatorSensitivity>(TaggedInt::ToUInt16(args.Values[4]));
  1730. }
  1731. if (!JavascriptOperators::IsUndefinedObject(args.Values[5]) && JavascriptBoolean::Is(args.Values[5]))
  1732. {
  1733. ignorePunctuation = (JavascriptBoolean::FromVar(args.Values[5])->GetValue() != 0);
  1734. }
  1735. if (!JavascriptOperators::IsUndefinedObject(args.Values[6]) && JavascriptBoolean::Is(args.Values[6]))
  1736. {
  1737. numeric = (JavascriptBoolean::FromVar(args.Values[6])->GetValue() != 0);
  1738. }
  1739. if (!JavascriptOperators::IsUndefinedObject(args.Values[7]) && TaggedInt::Is(args.Values[7]))
  1740. {
  1741. caseFirst = static_cast<CollatorCaseFirst>(TaggedInt::ToUInt16(args.Values[7]));
  1742. }
  1743. }
  1744. else
  1745. {
  1746. if (GetUserDefaultLocaleName(defaultLocale, _countof(defaultLocale)) != 0)
  1747. {
  1748. locale = defaultLocale;
  1749. }
  1750. else
  1751. {
  1752. JavascriptError::MapAndThrowError(scriptContext, HRESULT_FROM_WIN32(GetLastError()));
  1753. }
  1754. }
  1755. Assert(locale != nullptr);
  1756. Assert((int)sensitivity >= 0 && sensitivity < CollatorSensitivity::Max);
  1757. Assert((int)caseFirst >= 0 && caseFirst < CollatorCaseFirst::Max);
  1758. BEGIN_TEMP_ALLOCATOR(tempAllocator, scriptContext, _u("EntryIntl_CompareString"));
  1759. const char16 *left = nullptr;
  1760. charcount_t leftLen = 0;
  1761. if (UnicodeText::IsNormalizedString(UnicodeText::NormalizationForm::C, str1->GetSz(), str1->GetLength()))
  1762. {
  1763. left = str1->GetSz();
  1764. leftLen = str1->GetLength();
  1765. }
  1766. else
  1767. {
  1768. left = str1->GetNormalizedString(UnicodeText::NormalizationForm::C, tempAllocator, leftLen);
  1769. }
  1770. const char16 *right = nullptr;
  1771. charcount_t rightLen = 0;
  1772. if (UnicodeText::IsNormalizedString(UnicodeText::NormalizationForm::C, str2->GetSz(), str2->GetLength()))
  1773. {
  1774. right = str2->GetSz();
  1775. rightLen = str2->GetLength();
  1776. }
  1777. else
  1778. {
  1779. right = str2->GetNormalizedString(UnicodeText::NormalizationForm::C, tempAllocator, rightLen);
  1780. }
  1781. // CompareStringEx on Windows returns 0 for error, 1 if less, 2 if equal, 3 if greater
  1782. // Default to the strings being equal, because sorting with == causes no change in the order but converges, whereas < would cause an infinite loop.
  1783. int compareResult = 2;
  1784. HRESULT error = S_OK;
  1785. DWORD comparisonFlags = GetCompareStringComparisonFlags(sensitivity, ignorePunctuation, numeric);
  1786. compareResult = CompareStringEx(locale, comparisonFlags, left, leftLen, right, rightLen, NULL, NULL, 0);
  1787. error = HRESULT_FROM_WIN32(GetLastError());
  1788. END_TEMP_ALLOCATOR(tempAllocator, scriptContext);
  1789. if (compareResult == 0)
  1790. {
  1791. JavascriptError::MapAndThrowError(scriptContext, error);
  1792. }
  1793. return JavascriptNumber::ToVar(compareResult - 2, scriptContext);
  1794. #endif
  1795. }
  1796. Var IntlEngineInterfaceExtensionObject::EntryIntl_CurrencyDigits(RecyclableObject* function, CallInfo callInfo, ...)
  1797. {
  1798. EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
  1799. INTL_CHECK_ARGS(
  1800. args.Info.Count == 2 &&
  1801. JavascriptString::Is(args.Values[1])
  1802. );
  1803. const char16 *currencyCode = JavascriptString::UnsafeFromVar(args.Values[1])->GetSz();
  1804. #if defined(INTL_ICU)
  1805. UErrorCode status = U_ZERO_ERROR;
  1806. ScopedUNumberFormat fmt(unum_open(UNUM_CURRENCY, nullptr, 0, nullptr, nullptr, &status));
  1807. unum_setTextAttribute(fmt, UNUM_CURRENCY_CODE, reinterpret_cast<const UChar *>(currencyCode), -1, &status);
  1808. ICU_ASSERT(status, true);
  1809. int currencyDigits = unum_getAttribute(fmt, UNUM_FRACTION_DIGITS);
  1810. return JavascriptNumber::ToVar(currencyDigits, scriptContext);
  1811. #else
  1812. HRESULT hr;
  1813. AutoCOMPtr<NumberFormatting::ICurrencyFormatter> currencyFormatter(nullptr);
  1814. IfFailThrowHr(GetWindowsGlobalizationAdapter(scriptContext)->CreateCurrencyFormatterCode(scriptContext, currencyCode, &currencyFormatter));
  1815. AutoCOMPtr<NumberFormatting::INumberFormatterOptions> numberFormatterOptions;
  1816. IfFailThrowHr(currencyFormatter->QueryInterface(__uuidof(NumberFormatting::INumberFormatterOptions), reinterpret_cast<void**>(&numberFormatterOptions)));
  1817. Assert(numberFormatterOptions);
  1818. INT32 fractionDigits;
  1819. IfFailThrowHr(numberFormatterOptions->get_FractionDigits(&fractionDigits));
  1820. return JavascriptNumber::ToVar(fractionDigits, scriptContext);
  1821. #endif
  1822. }
  1823. #ifdef INTL_WINGLOB
  1824. //Helper, this just prepares based on fraction and integer format options
  1825. void IntlEngineInterfaceExtensionObject::prepareWithFractionIntegerDigits(ScriptContext* scriptContext, NumberFormatting::INumberRounderOption* rounderOptions,
  1826. NumberFormatting::INumberFormatterOptions* formatterOptions, uint16 minFractionDigits, uint16 maxFractionDigits, uint16 minIntegerDigits)
  1827. {
  1828. HRESULT hr;
  1829. WindowsGlobalizationAdapter* wga = GetWindowsGlobalizationAdapter(scriptContext);
  1830. AutoCOMPtr<NumberFormatting::INumberRounder> numberRounder(nullptr);
  1831. AutoCOMPtr<NumberFormatting::IIncrementNumberRounder> incrementNumberRounder(nullptr);
  1832. IfFailThrowHr(wga->CreateIncrementNumberRounder(scriptContext, &numberRounder));
  1833. IfFailThrowHr(numberRounder->QueryInterface(__uuidof(NumberFormatting::IIncrementNumberRounder), reinterpret_cast<void**>(&incrementNumberRounder)));
  1834. Assert(incrementNumberRounder);
  1835. IfFailThrowHr(incrementNumberRounder->put_RoundingAlgorithm(Windows::Globalization::NumberFormatting::RoundingAlgorithm::RoundingAlgorithm_RoundHalfAwayFromZero));
  1836. IfFailThrowHr(incrementNumberRounder->put_Increment(pow(10.0, -maxFractionDigits)));
  1837. IfFailThrowHr(rounderOptions->put_NumberRounder(numberRounder));
  1838. IfFailThrowHr(formatterOptions->put_FractionDigits(minFractionDigits));
  1839. IfFailThrowHr(formatterOptions->put_IntegerDigits(minIntegerDigits));
  1840. }
  1841. //Helper, this just prepares based on significant digits format options
  1842. void IntlEngineInterfaceExtensionObject::prepareWithSignificantDigits(ScriptContext* scriptContext, NumberFormatting::INumberRounderOption* rounderOptions, NumberFormatting::INumberFormatter *numberFormatter,
  1843. NumberFormatting::INumberFormatterOptions* formatterOptions, uint16 minSignificantDigits, uint16 maxSignificantDigits)
  1844. {
  1845. HRESULT hr;
  1846. WindowsGlobalizationAdapter* wga = GetWindowsGlobalizationAdapter(scriptContext);
  1847. AutoCOMPtr<NumberFormatting::INumberRounder> numberRounder(nullptr);
  1848. AutoCOMPtr<NumberFormatting::ISignificantDigitsNumberRounder> incrementNumberRounder(nullptr);
  1849. AutoCOMPtr<NumberFormatting::ISignificantDigitsOption> significantDigitsOptions(nullptr);
  1850. IfFailThrowHr(wga->CreateSignificantDigitsRounder(scriptContext, &numberRounder));
  1851. IfFailThrowHr(numberRounder->QueryInterface(__uuidof(NumberFormatting::ISignificantDigitsNumberRounder), reinterpret_cast<void**>(&incrementNumberRounder)));
  1852. Assert(incrementNumberRounder);
  1853. IfFailThrowHr(incrementNumberRounder->put_RoundingAlgorithm(Windows::Globalization::NumberFormatting::RoundingAlgorithm::RoundingAlgorithm_RoundHalfAwayFromZero));
  1854. IfFailThrowHr(incrementNumberRounder->put_SignificantDigits(maxSignificantDigits));
  1855. IfFailThrowHr(rounderOptions->put_NumberRounder(numberRounder));
  1856. IfFailThrowHr(numberFormatter->QueryInterface(__uuidof(NumberFormatting::ISignificantDigitsOption), reinterpret_cast<void**>(&significantDigitsOptions)));
  1857. IfFailThrowHr(significantDigitsOptions->put_SignificantDigits(minSignificantDigits));
  1858. Assert(significantDigitsOptions);
  1859. //Clear minimum fraction digits as in the case of percent 2 is supplied
  1860. IfFailThrowHr(formatterOptions->put_FractionDigits(0));
  1861. }
  1862. #endif
  1863. #ifdef INTL_ICU
  1864. // Rationale for this data structure: ICU reports back a tree of parts where each node in the tree
  1865. // has a type and a width, and there must be at least one node corresponding to each character in the tree
  1866. // (nodes can be wider than one character). Nodes can have children, and the parent-child relationship is
  1867. // that child node represents a more specific type for a given character range than the parent. Since ICU
  1868. // doesn't ever report "literal" parts of strings (like spaces or other extra characters), the root node in
  1869. // the tree will always be the entire width of the string with the type UnsetField, and we later map UnsetField
  1870. // to the "literal" part. Then, for a string like "US$ 1,000", there will be two child nodes, one of type
  1871. // currency with width [0, 3) and one of type integer with width [4, 9). The integer node will have a child
  1872. // of type group and width [6, 7). So the most specific type for characters 0 to 3 is currency, 3 to 4 is unset
  1873. // (literal), 4 to 5 is integer, 5 to 6 is group, and 6 to 9 is integer. This linear scan across the string,
  1874. // determining the part of consecutive spans of characters, is what the NumberFormat.prototype.formatToParts
  1875. // API needs to return to the user.
  1876. //
  1877. // I thought about this a bunch and I didn't like the idea of traversing an actual tree structure to get that
  1878. // information because it felt awkward to encode the "width" of nodes with specific meaning during traveral.
  1879. // So, I came up with an array structure where basically when we are told a part exists from position x to y,
  1880. // we can figure out what type used to apply to that span and update that section of the array with the new type.
  1881. // We skip over sections of the span [x, y) that have a type that doesn't match the start and end because that
  1882. // means we have already gotten a more specific part for that sub-span (for instance if we got a grouping
  1883. // separator before it's parent integer)
  1884. class NumberFormatPartsBuilder
  1885. {
  1886. private:
  1887. double num;
  1888. Field(const char16 *) formatted;
  1889. const charcount_t formattedLength;
  1890. Field(ScriptContext *) sc;
  1891. Field(UNumberFormatFields *) fields;
  1892. static const UNumberFormatFields UnsetField = static_cast<UNumberFormatFields>(0xFFFFFFFF);
  1893. JavascriptString *GetPartTypeString(UNumberFormatFields field)
  1894. {
  1895. JavascriptLibrary *library = sc->GetLibrary();
  1896. // this is outside the switch because MSVC doesn't like that UnsetField is not a valid enum value
  1897. if (field == UnsetField)
  1898. {
  1899. return library->GetIntlLiteralPartString();
  1900. }
  1901. switch (field)
  1902. {
  1903. case UNUM_INTEGER_FIELD:
  1904. {
  1905. if (JavascriptNumber::IsNan(num))
  1906. {
  1907. return library->GetIntlNanPartString();
  1908. }
  1909. else if (!NumberUtilities::IsFinite(num))
  1910. {
  1911. return library->GetIntlInfinityPartString();
  1912. }
  1913. else
  1914. {
  1915. return library->GetIntlIntegerPartString();
  1916. }
  1917. }
  1918. case UNUM_FRACTION_FIELD: return library->GetIntlFractionPartString();
  1919. case UNUM_DECIMAL_SEPARATOR_FIELD: return library->GetIntlDecimalPartString();
  1920. // The following three should only show up if UNUM_SCIENTIFIC is used, which Intl.NumberFormat doesn't currently use
  1921. case UNUM_EXPONENT_SYMBOL_FIELD: AssertOrFailFastMsg(false, "Unexpected exponent symbol field");
  1922. case UNUM_EXPONENT_SIGN_FIELD: AssertOrFailFastMsg(false, "Unexpected exponent sign field");
  1923. case UNUM_EXPONENT_FIELD: AssertOrFailFastMsg(false, "Unexpected exponent field");
  1924. case UNUM_GROUPING_SEPARATOR_FIELD: return library->GetIntlGroupPartString();
  1925. case UNUM_CURRENCY_FIELD: return library->GetIntlCurrencyPartString();
  1926. case UNUM_PERCENT_FIELD: return library->GetIntlPercentPartString();
  1927. // TODO(jahorto): Determine if this would ever be returned and what it would map to
  1928. case UNUM_PERMILL_FIELD: AssertOrFailFastMsg(false, "Unexpected permill field");
  1929. case UNUM_SIGN_FIELD: return num < 0 ? library->GetIntlMinusSignPartString() : library->GetIntlPlusSignPartString();
  1930. // At the ECMA-402 TC39 call for May 2017, it was decided that we should treat unmapped parts as type: "unknown"
  1931. default: return library->GetIntlUnknownPartString();
  1932. }
  1933. }
  1934. public:
  1935. NumberFormatPartsBuilder(double num, const char16 *formatted, charcount_t formattedLength, ScriptContext *scriptContext)
  1936. : num(num)
  1937. , formatted(formatted)
  1938. , formattedLength(formattedLength)
  1939. , sc(scriptContext)
  1940. , fields(RecyclerNewArrayLeaf(sc->GetRecycler(), UNumberFormatFields, formattedLength))
  1941. {
  1942. // this will allow InsertPart to tell what fields have been initialized or not, and will
  1943. // be the value of resulting { type: "literal" } fields in ToPartsArray
  1944. memset(fields, UnsetField, sizeof(UNumberFormatFields) * formattedLength);
  1945. }
  1946. // Note -- ICU reports fields as inclusive start, exclusive end, so thats how we handle the parameters here
  1947. void InsertPart(UNumberFormatFields field, int start, int end)
  1948. {
  1949. AssertOrFailFast(start >= 0);
  1950. AssertOrFailFast(start < end);
  1951. // the asserts above mean the cast to charcount_t is safe
  1952. charcount_t ccStart = static_cast<charcount_t>(start);
  1953. charcount_t ccEnd = static_cast<charcount_t>(end);
  1954. AssertOrFailFast(ccEnd <= formattedLength);
  1955. // Make sure that the part does not overlap/is a strict subset or superset of other fields
  1956. // The part builder could probably be built and tested to handle this structure not being so rigid,
  1957. // but its safer for now to make sure this is true.
  1958. UNumberFormatFields parentStartField = fields[ccStart];
  1959. UNumberFormatFields parentEndField = fields[ccEnd - 1];
  1960. AssertOrFailFast(parentStartField == parentEndField);
  1961. // Actually insert the part now
  1962. // Only overwrite fields in the span that match start and end, since fields that don't match are sub-parts that were already inserted
  1963. for (charcount_t i = ccStart; i < ccEnd; ++i)
  1964. {
  1965. if (fields[i] == parentStartField)
  1966. {
  1967. fields[i] = field;
  1968. }
  1969. }
  1970. }
  1971. JavascriptArray *ToPartsArray()
  1972. {
  1973. JavascriptArray *ret = sc->GetLibrary()->CreateArray(0);
  1974. int retIndex = 0;
  1975. // With the structure of the fields array, creating the resulting parts list to return to JS is simple
  1976. // Map set parts to the corresponding `type` value (see ECMA-402 #sec-partitionnumberpattern), and unset parts to the `literal` type
  1977. for (charcount_t start = 0; start < formattedLength; ++retIndex)
  1978. {
  1979. // At the top of the loop, fields[start] should always be different from fields[start - 1] (we should be at the start of a new part),
  1980. // since start is adjusted later in the loop to the end of the part
  1981. AssertOrFailFast(start == 0 || fields[start - 1] != fields[start]);
  1982. charcount_t end = start + 1;
  1983. while (end < formattedLength && fields[end] == fields[start])
  1984. {
  1985. ++end;
  1986. }
  1987. JavascriptString *partType = GetPartTypeString(fields[start]);
  1988. JavascriptString *partValue = JavascriptString::NewCopyBuffer(formatted + start, end - start, sc);
  1989. DynamicObject* part = sc->GetLibrary()->CreateObject();
  1990. JavascriptOperators::InitProperty(part, PropertyIds::type, partType);
  1991. JavascriptOperators::InitProperty(part, PropertyIds::value, partValue);
  1992. ret->SetItem(retIndex, part, PropertyOperationFlags::PropertyOperation_None);
  1993. start = end;
  1994. }
  1995. return ret;
  1996. }
  1997. };
  1998. #endif
  1999. Var IntlEngineInterfaceExtensionObject::EntryIntl_FormatNumber(RecyclableObject* function, CallInfo callInfo, ...)
  2000. {
  2001. EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
  2002. #if defined(INTL_ICU)
  2003. INTL_CHECK_ARGS(
  2004. args.Info.Count == 5 &&
  2005. (TaggedInt::Is(args[1]) || JavascriptNumber::Is(args[1])) &&
  2006. DynamicObject::Is(args[2]) &&
  2007. JavascriptBoolean::Is(args[3]) &&
  2008. JavascriptBoolean::Is(args[4])
  2009. );
  2010. double num = JavascriptConversion::ToNumber(args[1], scriptContext);
  2011. DynamicObject *state = DynamicObject::UnsafeFromVar(args[2]);
  2012. bool toParts = JavascriptBoolean::UnsafeFromVar(args[3])->GetValue();
  2013. bool forNumberPrototypeToLocaleString = JavascriptBoolean::UnsafeFromVar(args[4])->GetValue();
  2014. Var cachedUNumberFormat = nullptr; // cached by EntryIntl_CacheNumberFormat
  2015. AssertOrFailFast(state->GetInternalProperty(state, InternalPropertyIds::CachedUNumberFormat, &cachedUNumberFormat, NULL, scriptContext));
  2016. if (forNumberPrototypeToLocaleString)
  2017. {
  2018. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Number_Prototype_toLocaleString);
  2019. INTL_TRACE("Calling %f.toLocaleString(...)", num);
  2020. }
  2021. else if (toParts)
  2022. {
  2023. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(NumberFormat_Prototype_formatToParts);
  2024. INTL_TRACE("Calling NumberFormat.prototype.formatToParts(%f)", num);
  2025. }
  2026. else
  2027. {
  2028. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(NumberFormat_Prototype_format);
  2029. INTL_TRACE("Calling NumberFormat.prototype.format(%f)", num);
  2030. }
  2031. auto fmt = static_cast<FinalizableUNumberFormat *>(cachedUNumberFormat);
  2032. char16 *formatted = nullptr;
  2033. int formattedLen = 0;
  2034. if (!toParts)
  2035. {
  2036. EnsureBuffer([&](UChar *buf, int bufLen, UErrorCode *status)
  2037. {
  2038. return unum_formatDouble(*fmt, num, buf, bufLen, nullptr, status);
  2039. }, scriptContext->GetRecycler(), &formatted, &formattedLen);
  2040. return JavascriptString::NewWithBuffer(formatted, formattedLen, scriptContext);
  2041. }
  2042. #if defined(ICU_VERSION) && ICU_VERSION >= 61
  2043. UErrorCode status = U_ZERO_ERROR;
  2044. ScopedUFieldPositionIterator fpi(ufieldpositer_open(&status));
  2045. EnsureBuffer([&](UChar *buf, int bufLen, UErrorCode *status)
  2046. {
  2047. return unum_formatDoubleForFields(*fmt, num, buf, bufLen, fpi, status);
  2048. }, scriptContext->GetRecycler(), &formatted, &formattedLen);
  2049. NumberFormatPartsBuilder nfpb(num, formatted, formattedLen, scriptContext);
  2050. int partStart = 0;
  2051. int partEnd = 0;
  2052. int i = 0;
  2053. for (int kind = ufieldpositer_next(fpi, &partStart, &partEnd); kind >= 0; kind = ufieldpositer_next(fpi, &partStart, &partEnd), ++i)
  2054. {
  2055. nfpb.InsertPart(static_cast<UNumberFormatFields>(kind), partStart, partEnd);
  2056. }
  2057. return nfpb.ToPartsArray();
  2058. #else
  2059. JavascriptLibrary *library = scriptContext->GetLibrary();
  2060. JavascriptArray *ret = library->CreateArray(1);
  2061. DynamicObject* part = library->CreateObject();
  2062. EnsureBuffer([&](UChar *buf, int bufLen, UErrorCode *status)
  2063. {
  2064. return unum_formatDouble(*fmt, num, buf, bufLen, nullptr, status);
  2065. }, scriptContext->GetRecycler(), &formatted, &formattedLen);
  2066. JavascriptOperators::InitProperty(part, PropertyIds::type, library->GetIntlUnknownPartString());
  2067. JavascriptOperators::InitProperty(part, PropertyIds::value, JavascriptString::NewWithBuffer(formatted, formattedLen, scriptContext));
  2068. ret->SetItem(0, part, PropertyOperationFlags::PropertyOperation_None);
  2069. return ret;
  2070. #endif // #if ICU_VERSION >= 61 ... #else
  2071. #else
  2072. INTL_CHECK_ARGS(
  2073. args.Info.Count == 3 &&
  2074. (TaggedInt::Is(args.Values[1]) || JavascriptNumber::Is(args.Values[1])) &&
  2075. DynamicObject::Is(args.Values[2])
  2076. );
  2077. DynamicObject *options = DynamicObject::FromVar(args.Values[2]);
  2078. Var hiddenObject = nullptr;
  2079. AssertOrFailFastMsg(options->GetInternalProperty(options, Js::InternalPropertyIds::HiddenObject, &hiddenObject, NULL, scriptContext),
  2080. "EntryIntl_FormatNumber: Could not retrieve hiddenObject.");
  2081. DelayLoadWindowsGlobalization* wsl = scriptContext->GetThreadContext()->GetWindowsGlobalizationLibrary();
  2082. NumberFormatting::INumberFormatter *numberFormatter;
  2083. numberFormatter = static_cast<NumberFormatting::INumberFormatter *>(((AutoCOMJSObject *)hiddenObject)->GetInstance());
  2084. AutoHSTRING result;
  2085. HRESULT hr;
  2086. if (TaggedInt::Is(args.Values[1]))
  2087. {
  2088. IfFailThrowHr(numberFormatter->FormatInt(TaggedInt::ToInt32(args.Values[1]), &result));
  2089. }
  2090. else
  2091. {
  2092. IfFailThrowHr(numberFormatter->FormatDouble(JavascriptNumber::GetValue(args.Values[1]), &result));
  2093. }
  2094. PCWSTR strBuf = wsl->WindowsGetStringRawBuffer(*result, NULL);
  2095. if (strBuf == nullptr)
  2096. {
  2097. return scriptContext->GetLibrary()->GetUndefined();
  2098. }
  2099. else
  2100. {
  2101. JavascriptStringObject *retVal = scriptContext->GetLibrary()->CreateStringObject(Js::JavascriptString::NewCopySz(strBuf, scriptContext));
  2102. return retVal;
  2103. }
  2104. #endif
  2105. }
  2106. #ifdef INTL_ICU
  2107. // Implementation of ECMA 262 #sec-timeclip
  2108. // REVIEW(jahorto): Where is a better place for this function? JavascriptDate? DateUtilities? JavascriptConversion?
  2109. static double TimeClip(Var x)
  2110. {
  2111. double time = 0.0;
  2112. if (TaggedInt::Is(x))
  2113. {
  2114. time = TaggedInt::ToDouble(x);
  2115. }
  2116. else
  2117. {
  2118. AssertOrFailFast(JavascriptNumber::Is(x));
  2119. time = JavascriptNumber::GetValue(x);
  2120. // Only perform steps 1, 3, and 4 if the input was not a TaggedInt, since TaggedInts cant be infinite or -0
  2121. if (!NumberUtilities::IsFinite(time))
  2122. {
  2123. return NumberConstants::NaN;
  2124. }
  2125. // This performs both steps 3 and 4
  2126. time = JavascriptConversion::ToInteger(time);
  2127. }
  2128. // Step 2: If abs(time) > 8.64e15, return NaN.
  2129. if (Math::Abs(time) > 8.64e15)
  2130. {
  2131. return NumberConstants::NaN;
  2132. }
  2133. return time;
  2134. }
  2135. static void AddPartToPartsArray(ScriptContext *scriptContext, JavascriptArray *arr, int arrIndex, const char16 *src, int start, int end, JavascriptString *partType)
  2136. {
  2137. JavascriptString *partValue = JavascriptString::NewCopyBuffer(
  2138. src + start,
  2139. end - start,
  2140. scriptContext
  2141. );
  2142. DynamicObject* part = scriptContext->GetLibrary()->CreateObject();
  2143. JavascriptOperators::InitProperty(part, PropertyIds::type, partType);
  2144. JavascriptOperators::InitProperty(part, PropertyIds::value, partValue);
  2145. arr->SetItem(arrIndex, part, PropertyOperationFlags::PropertyOperation_None);
  2146. }
  2147. #endif
  2148. // For Windows Globalization, this function takes a number (date) and a state object and returns a string
  2149. // For ICU, this function takes a state object, number, and boolean for whether or not to format to parts.
  2150. // if args.Values[3] ~= true, an array of objects is returned; else, a string is returned
  2151. Var IntlEngineInterfaceExtensionObject::EntryIntl_FormatDateTime(RecyclableObject* function, CallInfo callInfo, ...)
  2152. {
  2153. EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
  2154. #ifdef INTL_WINGLOB
  2155. if (args.Info.Count < 3 || !(TaggedInt::Is(args.Values[1]) || JavascriptNumber::Is(args.Values[1])) || !DynamicObject::Is(args.Values[2]))
  2156. {
  2157. return scriptContext->GetLibrary()->GetUndefined();
  2158. }
  2159. Windows::Foundation::DateTime winDate;
  2160. HRESULT hr;
  2161. if (TaggedInt::Is(args.Values[1]))
  2162. {
  2163. hr = Js::DateUtilities::ES5DateToWinRTDate(TaggedInt::ToInt32(args.Values[1]), &(winDate.UniversalTime));
  2164. }
  2165. else
  2166. {
  2167. hr = Js::DateUtilities::ES5DateToWinRTDate(JavascriptNumber::GetValue(args.Values[1]), &(winDate.UniversalTime));
  2168. }
  2169. if (FAILED(hr))
  2170. {
  2171. HandleOOMSOEHR(hr);
  2172. // If conversion failed, double value is outside the range of WinRT DateTime
  2173. Js::JavascriptError::ThrowRangeError(scriptContext, JSERR_OutOfDateTimeRange);
  2174. }
  2175. DynamicObject* obj = DynamicObject::FromVar(args.Values[2]);
  2176. Var hiddenObject = nullptr;
  2177. AssertOrFailFastMsg(obj->GetInternalProperty(obj, Js::InternalPropertyIds::HiddenObject, &hiddenObject, NULL, scriptContext),
  2178. "EntryIntl_FormatDateTime: Could not retrieve hiddenObject.");
  2179. //We are going to perform the same check for timeZone as when caching the formatter.
  2180. Var propertyValue = nullptr;
  2181. AutoHSTRING result;
  2182. //If timeZone is undefined; then use the standard dateTimeFormatter to format in local time; otherwise use the IDateTimeFormatter2 to format using specified timezone (UTC)
  2183. if (!GetPropertyBuiltInFrom(obj, __timeZone) || JavascriptOperators::IsUndefinedObject(propertyValue))
  2184. {
  2185. DateTimeFormatting::IDateTimeFormatter *formatter = static_cast<DateTimeFormatting::IDateTimeFormatter *>(((AutoCOMJSObject *)hiddenObject)->GetInstance());
  2186. Assert(formatter);
  2187. IfFailThrowHr(formatter->Format(winDate, &result));
  2188. }
  2189. else
  2190. {
  2191. DateTimeFormatting::IDateTimeFormatter2 *formatter = static_cast<DateTimeFormatting::IDateTimeFormatter2 *>(((AutoCOMJSObject *)hiddenObject)->GetInstance());
  2192. Assert(formatter);
  2193. HSTRING timeZone;
  2194. HSTRING_HEADER timeZoneHeader;
  2195. // IsValidTimeZone() has already verified that this is JavascriptString.
  2196. JavascriptString* userDefinedTimeZoneId = JavascriptString::FromVar(propertyValue);
  2197. IfFailThrowHr(WindowsCreateStringReference(userDefinedTimeZoneId->GetSz(), userDefinedTimeZoneId->GetLength(), &timeZoneHeader, &timeZone));
  2198. Assert(timeZone);
  2199. IfFailThrowHr(formatter->FormatUsingTimeZone(winDate, timeZone, &result));
  2200. }
  2201. PCWSTR strBuf = scriptContext->GetThreadContext()->GetWindowsGlobalizationLibrary()->WindowsGetStringRawBuffer(*result, NULL);
  2202. return Js::JavascriptString::NewCopySz(strBuf, scriptContext);
  2203. #else
  2204. // This function vaguely implements ECMA 402 #sec-partitiondatetimepattern
  2205. INTL_CHECK_ARGS(
  2206. args.Info.Count == 5 &&
  2207. DynamicObject::Is(args[1]) &&
  2208. (TaggedInt::Is(args[2]) || JavascriptNumber::Is(args[2])) &&
  2209. JavascriptBoolean::Is(args[3]) &&
  2210. JavascriptBoolean::Is(args[4])
  2211. );
  2212. DynamicObject *state = DynamicObject::UnsafeFromVar(args[1]);
  2213. bool toParts = Js::JavascriptBoolean::UnsafeFromVar(args[3])->GetValue();
  2214. // 1. Let x be TimeClip(x)
  2215. // 2. If x is NaN, throw a RangeError exception
  2216. double date = TimeClip(args[2]);
  2217. if (JavascriptNumber::IsNan(date))
  2218. {
  2219. JavascriptError::ThrowRangeError(scriptContext, JSERR_InvalidDate);
  2220. }
  2221. bool forDatePrototypeToLocaleString = JavascriptBoolean::UnsafeFromVar(args[4])->GetValue();
  2222. if (forDatePrototypeToLocaleString)
  2223. {
  2224. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Date_Prototype_toLocaleString);
  2225. INTL_TRACE("Calling new Date(%f).toLocaleString(...)", date);
  2226. }
  2227. else if (toParts)
  2228. {
  2229. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(DateTimeFormat_Prototype_formatToParts);
  2230. INTL_TRACE("Calling DateTimeFormat.prototype.formatToParts(new Date(%f))", date);
  2231. }
  2232. else
  2233. {
  2234. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(DateTimeFormat_Prototype_format);
  2235. INTL_TRACE("Calling DateTimeFormat.prototype.format(new Date(%f))", date);
  2236. }
  2237. // Below, we lazy-initialize the backing UDateFormat on the first call to format{ToParts}
  2238. // On subsequent calls, the UDateFormat will be cached in state.CachedUDateFormat
  2239. Var cachedUDateFormat = nullptr;
  2240. FinalizableUDateFormat *dtf = nullptr;
  2241. UErrorCode status = U_ZERO_ERROR;
  2242. if (state->GetInternalProperty(state, InternalPropertyIds::CachedUDateFormat, &cachedUDateFormat, nullptr, scriptContext))
  2243. {
  2244. dtf = reinterpret_cast<FinalizableUDateFormat *>(cachedUDateFormat);
  2245. INTL_TRACE("Using previously cached UDateFormat (0x%x)", dtf);
  2246. }
  2247. else
  2248. {
  2249. JavascriptString *langtag = AssertStringProperty(state, PropertyIds::locale);
  2250. JavascriptString *timeZone = AssertStringProperty(state, PropertyIds::timeZone);
  2251. JavascriptString *pattern = AssertStringProperty(state, PropertyIds::pattern);
  2252. char localeID[ULOC_FULLNAME_CAPACITY] = { 0 };
  2253. LangtagToLocaleID(langtag, localeID);
  2254. dtf = FinalizableUDateFormat::New(scriptContext->GetRecycler(), udat_open(
  2255. UDAT_PATTERN,
  2256. UDAT_PATTERN,
  2257. localeID,
  2258. reinterpret_cast<const UChar *>(timeZone->GetSz()),
  2259. timeZone->GetLength(),
  2260. reinterpret_cast<const UChar *>(pattern->GetSz()),
  2261. pattern->GetLength(),
  2262. &status
  2263. ));
  2264. ICU_ASSERT(status, true);
  2265. // DateTimeFormat is expected to use the "proleptic Gregorian calendar", which means that the Julian calendar should never be used.
  2266. // To accomplish this, we can set the switchover date between julian/gregorian
  2267. // to the ECMAScript beginning of time, which is -8.64e15 according to ecma262 #sec-time-values-and-time-range
  2268. UCalendar *cal = const_cast<UCalendar *>(udat_getCalendar(*dtf));
  2269. const char *calType = ucal_getType(cal, &status);
  2270. ICU_ASSERT(status, calType != nullptr);
  2271. if (strcmp(calType, "gregorian") == 0)
  2272. {
  2273. double beginningOfTime = -8.64e15;
  2274. ucal_setGregorianChange(cal, beginningOfTime, &status);
  2275. double actualGregorianChange = ucal_getGregorianChange(cal, &status);
  2276. ICU_ASSERT(status, beginningOfTime == actualGregorianChange);
  2277. }
  2278. INTL_TRACE("Caching new UDateFormat (0x%x) with langtag=%s, pattern=%s, timezone=%s", dtf, langtag->GetSz(), pattern->GetSz(), timeZone->GetSz());
  2279. // cache dtf for later use (so that the condition that brought us here returns true for future calls)
  2280. state->SetInternalProperty(
  2281. InternalPropertyIds::CachedUDateFormat,
  2282. dtf,
  2283. PropertyOperationFlags::PropertyOperation_None,
  2284. nullptr
  2285. );
  2286. }
  2287. // We intentionally special-case the following two calls to EnsureBuffer to allow zero-length strings.
  2288. // See comment in GetPatternForSkeleton.
  2289. char16 *formatted = nullptr;
  2290. int formattedLen = 0;
  2291. if (!toParts)
  2292. {
  2293. // if we aren't formatting to parts, we simply want to call udat_format with retry
  2294. EnsureBuffer([&](UChar *buf, int bufLen, UErrorCode *status)
  2295. {
  2296. return udat_format(*dtf, date, buf, bufLen, nullptr, status);
  2297. }, scriptContext->GetRecycler(), &formatted, &formattedLen, /* allowZeroLengthStrings */ true);
  2298. return JavascriptString::NewWithBuffer(formatted, formattedLen, scriptContext);
  2299. }
  2300. // The rest of this function most closely corresponds to ECMA 402 #sec-partitiondatetimepattern
  2301. ScopedUFieldPositionIterator fpi(ufieldpositer_open(&status));
  2302. ICU_ASSERT(status, true);
  2303. EnsureBuffer([&](UChar *buf, int bufLen, UErrorCode *status)
  2304. {
  2305. return udat_formatForFields(*dtf, date, buf, bufLen, fpi, status);
  2306. }, scriptContext->GetRecycler(), &formatted, &formattedLen, /* allowZeroLengthStrings */ true);
  2307. JavascriptLibrary *library = scriptContext->GetLibrary();
  2308. JavascriptArray* ret = library->CreateArray(0);
  2309. int partStart = 0;
  2310. int partEnd = 0;
  2311. int lastPartEnd = 0;
  2312. int i = 0;
  2313. for (
  2314. int kind = ufieldpositer_next(fpi, &partStart, &partEnd);
  2315. kind >= 0;
  2316. kind = ufieldpositer_next(fpi, &partStart, &partEnd), ++i
  2317. )
  2318. {
  2319. Assert(partStart < partEnd && partEnd <= formattedLen);
  2320. JavascriptString *typeString = nullptr;
  2321. UDateFormatField fieldKind = (UDateFormatField)kind;
  2322. switch (fieldKind)
  2323. {
  2324. case UDAT_ERA_FIELD:
  2325. typeString = library->GetIntlEraPartString(); break;
  2326. case UDAT_YEAR_FIELD:
  2327. case UDAT_EXTENDED_YEAR_FIELD:
  2328. case UDAT_YEAR_NAME_FIELD:
  2329. typeString = library->GetIntlYearPartString(); break;
  2330. case UDAT_MONTH_FIELD:
  2331. case UDAT_STANDALONE_MONTH_FIELD:
  2332. typeString = library->GetIntlMonthPartString(); break;
  2333. case UDAT_DATE_FIELD:
  2334. typeString = library->GetIntlDayPartString(); break;
  2335. case UDAT_HOUR_OF_DAY1_FIELD:
  2336. case UDAT_HOUR_OF_DAY0_FIELD:
  2337. case UDAT_HOUR1_FIELD:
  2338. case UDAT_HOUR0_FIELD:
  2339. typeString = library->GetIntlHourPartString(); break;
  2340. case UDAT_MINUTE_FIELD:
  2341. typeString = library->GetIntlMinutePartString(); break;
  2342. case UDAT_SECOND_FIELD:
  2343. typeString = library->GetIntlSecondPartString(); break;
  2344. case UDAT_DAY_OF_WEEK_FIELD:
  2345. case UDAT_STANDALONE_DAY_FIELD:
  2346. case UDAT_DOW_LOCAL_FIELD:
  2347. typeString = library->GetIntlWeekdayPartString(); break;
  2348. case UDAT_AM_PM_FIELD:
  2349. typeString = library->GetIntlDayPeriodPartString(); break;
  2350. case UDAT_TIMEZONE_FIELD:
  2351. case UDAT_TIMEZONE_RFC_FIELD:
  2352. case UDAT_TIMEZONE_GENERIC_FIELD:
  2353. case UDAT_TIMEZONE_SPECIAL_FIELD:
  2354. case UDAT_TIMEZONE_LOCALIZED_GMT_OFFSET_FIELD:
  2355. case UDAT_TIMEZONE_ISO_FIELD:
  2356. case UDAT_TIMEZONE_ISO_LOCAL_FIELD:
  2357. typeString = library->GetIntlTimeZoneNamePartString(); break;
  2358. #if defined(ICU_VERSION) && ICU_VERSION == 55
  2359. case UDAT_TIME_SEPARATOR_FIELD:
  2360. // ICU 55 (Ubuntu 16.04 system default) has the ":" in "5:23 PM" as a special field
  2361. // Intl should just treat this as a literal
  2362. typeString = library->GetIntlLiteralPartString(); break;
  2363. #endif
  2364. default:
  2365. typeString = library->GetIntlUnknownPartString(); break;
  2366. }
  2367. if (partStart > lastPartEnd)
  2368. {
  2369. // formatForFields does not report literal fields directly, so we have to detect them
  2370. // by seeing if the current part starts after the previous one ended
  2371. AddPartToPartsArray(scriptContext, ret, i, formatted, lastPartEnd, partStart, library->GetIntlLiteralPartString());
  2372. i += 1;
  2373. }
  2374. AddPartToPartsArray(scriptContext, ret, i, formatted, partStart, partEnd, typeString);
  2375. lastPartEnd = partEnd;
  2376. }
  2377. // Sometimes, there can be a literal at the end of the string, such as when formatting just the year in
  2378. // the chinese calendar, where the pattern string will be `r(U)`. The trailing `)` will be a literal
  2379. if (lastPartEnd != formattedLen)
  2380. {
  2381. AssertOrFailFast(lastPartEnd < formattedLen);
  2382. // `i` was incremented by the consequence of the last iteration of the for loop
  2383. AddPartToPartsArray(scriptContext, ret, i, formatted, lastPartEnd, formattedLen, library->GetIntlLiteralPartString());
  2384. }
  2385. return ret;
  2386. #endif
  2387. }
  2388. Var IntlEngineInterfaceExtensionObject::EntryIntl_GetPatternForSkeleton(RecyclableObject *function, CallInfo callInfo, ...)
  2389. {
  2390. #ifdef INTL_ICU
  2391. EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
  2392. INTL_CHECK_ARGS(args.Info.Count == 3 && JavascriptString::Is(args.Values[1]) && JavascriptString::Is(args.Values[2]));
  2393. JavascriptString *langtag = JavascriptString::UnsafeFromVar(args.Values[1]);
  2394. JavascriptString *skeleton = JavascriptString::UnsafeFromVar(args.Values[2]);
  2395. UErrorCode status = U_ZERO_ERROR;
  2396. char localeID[ULOC_FULLNAME_CAPACITY] = { 0 };
  2397. LangtagToLocaleID(langtag, localeID);
  2398. // See https://github.com/tc39/ecma402/issues/225
  2399. // When picking a format, we should be using the locale data of the basename of the resolved locale,
  2400. // compared to when we actually format the date using the format string, where we use the full locale including extensions
  2401. //
  2402. // ECMA 402 #sec-initializedatetimeformat
  2403. // 10: Let localeData be %DateTimeFormat%.[[LocaleData]].
  2404. // 11: Let r be ResolveLocale( %DateTimeFormat%.[[AvailableLocales]], requestedLocales, opt, %DateTimeFormat%.[[RelevantExtensionKeys]], localeData).
  2405. // 16: Let dataLocale be r.[[dataLocale]].
  2406. // 23: Let dataLocaleData be localeData.[[<dataLocale>]].
  2407. // 24: Let formats be dataLocaleData.[[formats]].
  2408. char baseLocaleID[ULOC_FULLNAME_CAPACITY] = { 0 };
  2409. int baseLocaleIDLength = uloc_getBaseName(localeID, baseLocaleID, _countof(baseLocaleID), &status);
  2410. ICU_ASSERT(status, baseLocaleIDLength > 0 && baseLocaleIDLength < ULOC_FULLNAME_CAPACITY);
  2411. INTL_TRACE("Converted input langtag '%s' to base locale ID '%S' for pattern generation", langtag->GetSz(), baseLocaleID);
  2412. ScopedUDateTimePatternGenerator dtpg(udatpg_open(baseLocaleID, &status));
  2413. ICU_ASSERT(status, true);
  2414. char16 *formatted = nullptr;
  2415. int formattedLen = 0;
  2416. // OS#17513493 (OSS-Fuzz 7950): It is possible for the skeleton to be a zero-length string
  2417. // because [[Get]] operations are performed on the options object twice, according to spec.
  2418. // Follow-up spec discussion here: https://github.com/tc39/ecma402/issues/237.
  2419. // We need to special-case this because calling udatpg_getBestPatternWithOptions on an empty skeleton
  2420. // will produce an empty pattern, which causes an assert in EnsureBuffer by default.
  2421. // As a result, we pass a final optional parameter to EnsureBuffer to say that zero-length results are OK.
  2422. // TODO(jahorto): re-visit this workaround and the one in FormatDateTime upon resolution of the spec issue.
  2423. EnsureBuffer([&](UChar *buf, int bufLen, UErrorCode *status)
  2424. {
  2425. return udatpg_getBestPatternWithOptions(
  2426. dtpg,
  2427. reinterpret_cast<const UChar *>(skeleton->GetSz()),
  2428. skeleton->GetLength(),
  2429. UDATPG_MATCH_ALL_FIELDS_LENGTH,
  2430. buf,
  2431. bufLen,
  2432. status
  2433. );
  2434. }, scriptContext->GetRecycler(), &formatted, &formattedLen, /* allowZeroLengthStrings */ true);
  2435. INTL_TRACE("Best pattern '%s' will be used for skeleton '%s' and langtag '%s'", formatted, skeleton->GetSz(), langtag->GetSz());
  2436. return JavascriptString::NewWithBuffer(formatted, formattedLen, scriptContext);
  2437. #else
  2438. AssertOrFailFastMsg(false, "GetPatternForSkeleton is not implemented outside of ICU");
  2439. return nullptr;
  2440. #endif
  2441. }
  2442. // given a timezone name as an argument, this will return a canonicalized version of that name, or undefined if the timezone is invalid
  2443. Var IntlEngineInterfaceExtensionObject::EntryIntl_ValidateAndCanonicalizeTimeZone(RecyclableObject* function, CallInfo callInfo, ...)
  2444. {
  2445. EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
  2446. INTL_CHECK_ARGS(args.Info.Count == 2 && JavascriptString::Is(args.Values[1]));
  2447. JavascriptString *tz = JavascriptString::FromVar(args.Values[1]);
  2448. #ifdef INTL_WINGLOB
  2449. AutoHSTRING canonicalizedTimeZone;
  2450. boolean isValidTimeZone = GetWindowsGlobalizationAdapter(scriptContext)->ValidateAndCanonicalizeTimeZone(scriptContext, tz->GetSz(), &canonicalizedTimeZone);
  2451. if (isValidTimeZone)
  2452. {
  2453. DelayLoadWindowsGlobalization* wsl = scriptContext->GetThreadContext()->GetWindowsGlobalizationLibrary();
  2454. PCWSTR strBuf = wsl->WindowsGetStringRawBuffer(*canonicalizedTimeZone, NULL);
  2455. return Js::JavascriptString::NewCopySz(strBuf, scriptContext);
  2456. }
  2457. else
  2458. {
  2459. return scriptContext->GetLibrary()->GetUndefined();
  2460. }
  2461. #else
  2462. UErrorCode status = U_ZERO_ERROR;
  2463. // TODO(jahorto): Is this the list of timeZones that we want? How is this different from
  2464. // the other two enum values or ucal_openTimeZones?
  2465. ScopedUEnumeration available(ucal_openTimeZoneIDEnumeration(UCAL_ZONE_TYPE_ANY, nullptr, nullptr, &status));
  2466. int availableLength = uenum_count(available, &status);
  2467. ICU_ASSERT(status, availableLength > 0);
  2468. charcount_t matchLen = 0;
  2469. UChar match[100] = { 0 };
  2470. for (int a = 0; a < availableLength; ++a)
  2471. {
  2472. int curLen = -1;
  2473. const UChar *cur = uenum_unext(available, &curLen, &status);
  2474. ICU_ASSERT(status, true);
  2475. if (curLen == 0)
  2476. {
  2477. // OS#17175014: in rare cases, ICU will return U_ZERO_ERROR and a valid `cur` string but a length of 0
  2478. // This only happens in an OOM during uenum_(u)next
  2479. // Tracked by ICU: http://bugs.icu-project.org/trac/ticket/13739
  2480. Throw::OutOfMemory();
  2481. }
  2482. AssertOrFailFast(curLen > 0);
  2483. if (_wcsicmp(reinterpret_cast<const char16 *>(cur), tz->GetSz()) == 0)
  2484. {
  2485. ucal_getCanonicalTimeZoneID(cur, curLen, match, _countof(match), nullptr, &status);
  2486. ICU_ASSERT(status, true);
  2487. size_t len = wcslen(reinterpret_cast<const char16 *>(match));
  2488. AssertMsg(len < MaxCharCount, "Returned canonicalized timezone is far too long");
  2489. matchLen = static_cast<charcount_t>(len);
  2490. break;
  2491. }
  2492. }
  2493. if (matchLen == 0)
  2494. {
  2495. return scriptContext->GetLibrary()->GetUndefined();
  2496. }
  2497. return JavascriptString::NewCopyBuffer(reinterpret_cast<const char16 *>(match), matchLen, scriptContext);
  2498. #endif
  2499. }
  2500. // returns the current system time zone
  2501. Var IntlEngineInterfaceExtensionObject::EntryIntl_GetDefaultTimeZone(RecyclableObject* function, CallInfo callInfo, ...)
  2502. {
  2503. EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
  2504. #ifdef INTL_WINGLOB
  2505. WindowsGlobalizationAdapter* wga = GetWindowsGlobalizationAdapter(scriptContext);
  2506. DelayLoadWindowsGlobalization* wsl = scriptContext->GetThreadContext()->GetWindowsGlobalizationLibrary();
  2507. AutoHSTRING str;
  2508. HRESULT hr;
  2509. if (FAILED(hr = wga->GetDefaultTimeZoneId(scriptContext, &str)))
  2510. {
  2511. HandleOOMSOEHR(hr);
  2512. //If we can't get default timeZone, return undefined.
  2513. return scriptContext->GetLibrary()->GetUndefined();
  2514. }
  2515. PCWSTR strBuf = wsl->WindowsGetStringRawBuffer(*str, NULL);
  2516. return Js::JavascriptString::NewCopySz(strBuf, scriptContext);
  2517. #else
  2518. int timeZoneLen = 0;
  2519. char16 *timeZone = nullptr;
  2520. EnsureBuffer([&](UChar *buf, int bufLen, UErrorCode *status)
  2521. {
  2522. return ucal_getDefaultTimeZone(buf, bufLen, status);
  2523. }, scriptContext->GetRecycler(), &timeZone, &timeZoneLen);
  2524. return JavascriptString::NewWithBuffer(timeZone, timeZoneLen, scriptContext);
  2525. #endif
  2526. }
  2527. #ifdef INTL_ICU
  2528. static FinalizableUPluralRules *GetOrCreateCachedUPluralRules(DynamicObject *stateObject, ScriptContext *scriptContext)
  2529. {
  2530. Var cachedUPluralRules = nullptr;
  2531. FinalizableUPluralRules *pr = nullptr;
  2532. if (stateObject->GetInternalProperty(stateObject, InternalPropertyIds::CachedUPluralRules, &cachedUPluralRules, nullptr, scriptContext))
  2533. {
  2534. pr = reinterpret_cast<FinalizableUPluralRules *>(cachedUPluralRules);
  2535. INTL_TRACE("Using previously cached UPluralRules (0x%x)", pr);
  2536. }
  2537. else
  2538. {
  2539. UErrorCode status = U_ZERO_ERROR;
  2540. JavascriptString *langtag = AssertStringProperty(stateObject, PropertyIds::locale);
  2541. JavascriptString *type = AssertStringProperty(stateObject, PropertyIds::type);
  2542. UPluralType prType = UPLURAL_TYPE_CARDINAL;
  2543. if (wcscmp(type->GetSz(), _u("ordinal")) == 0)
  2544. {
  2545. prType = UPLURAL_TYPE_ORDINAL;
  2546. }
  2547. else
  2548. {
  2549. AssertOrFailFast(wcscmp(type->GetSz(), _u("cardinal")) == 0);
  2550. }
  2551. char localeID[ULOC_FULLNAME_CAPACITY] = { 0 };
  2552. LangtagToLocaleID(langtag, localeID);
  2553. pr = FinalizableUPluralRules::New(scriptContext->GetRecycler(), uplrules_openForType(localeID, prType, &status));
  2554. ICU_ASSERT(status, true);
  2555. INTL_TRACE("Caching UPluralRules object (0x%x) with langtag %s and type %s", pr, langtag->GetSz(), type->GetSz());
  2556. stateObject->SetInternalProperty(InternalPropertyIds::CachedUPluralRules, pr, PropertyOperationFlags::PropertyOperation_None, nullptr);
  2557. }
  2558. return pr;
  2559. }
  2560. #endif
  2561. // This method implements Step 13 and 14 of ECMA 402 #sec-initializepluralrules
  2562. Var IntlEngineInterfaceExtensionObject::EntryIntl_PluralRulesKeywords(RecyclableObject *function, CallInfo callInfo, ...)
  2563. {
  2564. #ifdef INTL_ICU
  2565. EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
  2566. INTL_CHECK_ARGS(args.Info.Count == 2 && DynamicObject::Is(args[1]));
  2567. JavascriptArray *ret = scriptContext->GetLibrary()->CreateArray(0);
  2568. // uplrules_getKeywords is only stable since ICU 61.
  2569. // For ICU < 61, we can fake it by creating an array of ["other"], which
  2570. // uplrules_getKeywords is guaranteed to return at minimum.
  2571. // This array is only used in resolved options, so the majority of the functionality can remain (namely, select() still works)
  2572. #if defined(ICU_VERSION) && ICU_VERSION >= 61
  2573. DynamicObject *state = DynamicObject::UnsafeFromVar(args[1]);
  2574. FinalizableUPluralRules *pr = GetOrCreateCachedUPluralRules(state, scriptContext);
  2575. UErrorCode status = U_ZERO_ERROR;
  2576. ScopedUEnumeration keywords(uplrules_getKeywords(*pr, &status));
  2577. ICU_ASSERT(status, true);
  2578. ForEachUEnumeration16(keywords, [&](int index, const char16 *kw, charcount_t kwLength)
  2579. {
  2580. ret->SetItem(index, JavascriptString::NewCopyBuffer(kw, kwLength, scriptContext), PropertyOperation_None);
  2581. });
  2582. #else
  2583. ret->SetItem(0, scriptContext->GetLibrary()->GetIntlPluralRulesOtherString(), PropertyOperation_None);
  2584. #endif
  2585. return ret;
  2586. #else
  2587. AssertOrFailFastMsg(false, "Intl-WinGlob should not be using PluralRulesKeywords");
  2588. return nullptr;
  2589. #endif
  2590. }
  2591. // This method roughly implements ECMA 402 #sec-pluralruleselect, except ICU takes care of handling the operand logic for us
  2592. Var IntlEngineInterfaceExtensionObject::EntryIntl_PluralRulesSelect(RecyclableObject *function, CallInfo callInfo, ...)
  2593. {
  2594. #ifdef INTL_ICU
  2595. EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
  2596. INTL_CHECK_ARGS(args.Info.Count == 3 && DynamicObject::Is(args[1]));
  2597. DynamicObject *state = DynamicObject::UnsafeFromVar(args[1]);
  2598. double n = 0.0;
  2599. if (TaggedInt::Is(args[2]))
  2600. {
  2601. n = TaggedInt::ToDouble(args[2]);
  2602. }
  2603. else
  2604. {
  2605. AssertOrFailFast(JavascriptNumber::Is(args[2]));
  2606. n = JavascriptNumber::GetValue(args[2]);
  2607. }
  2608. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(PluralRules_Prototype_select);
  2609. INTL_TRACE("Calling PluralRules.prototype.select(%f)", n);
  2610. UErrorCode status = U_ZERO_ERROR;
  2611. FinalizableUPluralRules *pr = GetOrCreateCachedUPluralRules(state, scriptContext);
  2612. // ICU has an internal API, uplrules_selectWithFormat, that is equivalent to uplrules_select but will respect digit options of the passed UNumberFormat.
  2613. // Since its an internal API, we can't use it -- however, we can work around it by creating a UNumberFormat with provided digit options,
  2614. // formatting the requested number to a string, and then converting the string back to a double which we can pass to uplrules_select.
  2615. // This workaround was suggested during the May 2018 ECMA-402 discussion.
  2616. // The below is similar to GetOrCreateCachedUPluralRules, but since creating a UNumberFormat for Intl.NumberFormat is much more involved and no one else
  2617. // uses this functionality, it makes more sense to me to just put the logic inline.
  2618. Var cachedUNumberFormat = nullptr;
  2619. FinalizableUNumberFormat *nf = nullptr;
  2620. if (state->GetInternalProperty(state, InternalPropertyIds::CachedUNumberFormat, &cachedUNumberFormat, nullptr, scriptContext))
  2621. {
  2622. nf = reinterpret_cast<FinalizableUNumberFormat *>(cachedUNumberFormat);
  2623. INTL_TRACE("Using previously cached UNumberFormat (0x%x)", nf);
  2624. }
  2625. else
  2626. {
  2627. char localeID[ULOC_FULLNAME_CAPACITY] = { 0 };
  2628. LangtagToLocaleID(AssertStringProperty(state, PropertyIds::locale), localeID);
  2629. nf = FinalizableUNumberFormat::New(scriptContext->GetRecycler(), unum_open(UNUM_DECIMAL, nullptr, 0, localeID, nullptr, &status));
  2630. SetUNumberFormatDigitOptions(*nf, state);
  2631. INTL_TRACE("Caching UNumberFormat object (0x%x) with localeID %S", nf, localeID);
  2632. state->SetInternalProperty(InternalPropertyIds::CachedUNumberFormat, nf, PropertyOperationFlags::PropertyOperation_None, nullptr);
  2633. }
  2634. char16 *formattedN = nullptr;
  2635. int formattedNLength = 0;
  2636. EnsureBuffer([&](UChar *buf, int bufLen, UErrorCode *status)
  2637. {
  2638. return unum_formatDouble(*nf, n, buf, bufLen, nullptr, status);
  2639. }, scriptContext->GetRecycler(), &formattedN, &formattedNLength);
  2640. double nWithOptions = unum_parseDouble(*nf, reinterpret_cast<UChar *>(formattedN), formattedNLength, nullptr, &status);
  2641. double roundtripDiff = n - nWithOptions;
  2642. ICU_ASSERT(status, roundtripDiff <= 1.0 && roundtripDiff >= -1.0);
  2643. char16 *selected = nullptr;
  2644. int selectedLength = 0;
  2645. EnsureBuffer([&](UChar *buf, int bufLen, UErrorCode *status)
  2646. {
  2647. return uplrules_select(*pr, nWithOptions, buf, bufLen, status);
  2648. }, scriptContext->GetRecycler(), &selected, &selectedLength);
  2649. return JavascriptString::NewWithBuffer(selected, static_cast<charcount_t>(selectedLength), scriptContext);
  2650. #else
  2651. AssertOrFailFastMsg(false, "Intl-WinGlob should not be using PluralRulesSelect");
  2652. return nullptr;
  2653. #endif
  2654. }
  2655. /*
  2656. * This function registers built in functions when Intl initializes.
  2657. * Call with (Function : toRegister, integer : id)
  2658. * ID Mappings:
  2659. * - 0 for Date.prototype.toLocaleString
  2660. * - 1 for Date.prototype.toLocaleDateString
  2661. * - 2 for Date.prototype.toLocaleTimeString
  2662. * - 3 for Number.prototype.toLocaleString
  2663. * - 4 for String.prototype.localeCompare
  2664. */
  2665. Var IntlEngineInterfaceExtensionObject::EntryIntl_RegisterBuiltInFunction(RecyclableObject* function, CallInfo callInfo, ...)
  2666. {
  2667. // Don't put this in a header or add it to the namespace even in this file. Keep it to the minimum scope needed.
  2668. enum class IntlBuiltInFunctionID : int32 {
  2669. Min = 0,
  2670. DateToLocaleString = Min,
  2671. DateToLocaleDateString,
  2672. DateToLocaleTimeString,
  2673. NumberToLocaleString,
  2674. StringLocaleCompare,
  2675. Max
  2676. };
  2677. EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
  2678. // This function will only be used during the construction of the Intl object, hence Asserts are in place.
  2679. Assert(args.Info.Count >= 3 && JavascriptFunction::Is(args.Values[1]) && TaggedInt::Is(args.Values[2]));
  2680. JavascriptFunction *func = JavascriptFunction::FromVar(args.Values[1]);
  2681. int32 id = TaggedInt::ToInt32(args.Values[2]);
  2682. Assert(id >= (int32)IntlBuiltInFunctionID::Min && id < (int32)IntlBuiltInFunctionID::Max);
  2683. EngineInterfaceObject* nativeEngineInterfaceObj = scriptContext->GetLibrary()->GetEngineInterfaceObject();
  2684. IntlEngineInterfaceExtensionObject* extensionObject = static_cast<IntlEngineInterfaceExtensionObject*>(nativeEngineInterfaceObj->GetEngineExtension(EngineInterfaceExtensionKind_Intl));
  2685. IntlBuiltInFunctionID functionID = static_cast<IntlBuiltInFunctionID>(id);
  2686. switch (functionID)
  2687. {
  2688. case IntlBuiltInFunctionID::DateToLocaleString:
  2689. extensionObject->dateToLocaleString = func;
  2690. break;
  2691. case IntlBuiltInFunctionID::DateToLocaleDateString:
  2692. extensionObject->dateToLocaleDateString = func;
  2693. break;
  2694. case IntlBuiltInFunctionID::DateToLocaleTimeString:
  2695. extensionObject->dateToLocaleTimeString = func;
  2696. break;
  2697. case IntlBuiltInFunctionID::NumberToLocaleString:
  2698. extensionObject->numberToLocaleString = func;
  2699. break;
  2700. case IntlBuiltInFunctionID::StringLocaleCompare:
  2701. extensionObject->stringLocaleCompare = func;
  2702. break;
  2703. default:
  2704. AssertMsg(false, "functionID was not one of the allowed values. The previous assert should catch this.");
  2705. break;
  2706. }
  2707. // Don't need to return anything
  2708. return scriptContext->GetLibrary()->GetUndefined();
  2709. }
  2710. Var IntlEngineInterfaceExtensionObject::EntryIntl_GetHiddenObject(RecyclableObject* function, CallInfo callInfo, ...)
  2711. {
  2712. EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
  2713. if (callInfo.Count < 2 || !DynamicObject::Is(args.Values[1]))
  2714. {
  2715. return scriptContext->GetLibrary()->GetUndefined();
  2716. }
  2717. DynamicObject* obj = DynamicObject::FromVar(args.Values[1]);
  2718. Var hiddenObject = nullptr;
  2719. if (!obj->GetInternalProperty(obj, Js::InternalPropertyIds::HiddenObject, &hiddenObject, NULL, scriptContext))
  2720. {
  2721. return scriptContext->GetLibrary()->GetUndefined();
  2722. }
  2723. return hiddenObject;
  2724. }
  2725. Var IntlEngineInterfaceExtensionObject::EntryIntl_SetHiddenObject(RecyclableObject* function, CallInfo callInfo, ...)
  2726. {
  2727. EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
  2728. if (callInfo.Count < 3 || !DynamicObject::Is(args.Values[1]) || !DynamicObject::Is(args.Values[2]))
  2729. {
  2730. return scriptContext->GetLibrary()->GetUndefined();
  2731. }
  2732. DynamicObject* obj = DynamicObject::FromVar(args.Values[1]);
  2733. DynamicObject* value = DynamicObject::FromVar(args.Values[2]);
  2734. if (obj->SetInternalProperty(Js::InternalPropertyIds::HiddenObject, value, Js::PropertyOperationFlags::PropertyOperation_None, NULL))
  2735. {
  2736. return scriptContext->GetLibrary()->GetTrue();
  2737. }
  2738. else
  2739. {
  2740. return scriptContext->GetLibrary()->GetFalse();
  2741. }
  2742. }
  2743. #endif
  2744. }
  2745. #endif