2
0

IntlEngineInterfaceExtensionObject.cpp 145 KB

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