SourceTextModuleRecord.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "RuntimeLanguagePch.h"
  6. #include "Types/PropertyIndexRanges.h"
  7. #include "Types/SimpleDictionaryPropertyDescriptor.h"
  8. #include "Types/SimpleDictionaryTypeHandler.h"
  9. #include "ModuleNamespace.h"
  10. #include "Library/JavascriptPromise.h"
  11. namespace Js
  12. {
  13. const uint32 ModuleRecordBase::ModuleMagicNumber = *(const uint32*)"Mode";
  14. SourceTextModuleRecord::SourceTextModuleRecord(ScriptContext* scriptContext) :
  15. ModuleRecordBase(scriptContext->GetLibrary()),
  16. scriptContext(scriptContext),
  17. parseTree(nullptr),
  18. parser(nullptr),
  19. pSourceInfo(nullptr),
  20. rootFunction(nullptr),
  21. requestedModuleList(nullptr),
  22. importRecordList(nullptr),
  23. localExportRecordList(nullptr),
  24. indirectExportRecordList(nullptr),
  25. starExportRecordList(nullptr),
  26. childrenModuleSet(nullptr),
  27. parentModuleList(nullptr),
  28. localExportMapByExportName(nullptr),
  29. localExportMapByLocalName(nullptr),
  30. localExportIndexList(nullptr),
  31. normalizedSpecifier(nullptr),
  32. moduleUrl(nullptr),
  33. errorObject(nullptr),
  34. hostDefined(nullptr),
  35. exportedNames(nullptr),
  36. resolvedExportMap(nullptr),
  37. wasParsed(false),
  38. wasDeclarationInitialized(false),
  39. parentsNotified(false),
  40. isRootModule(false),
  41. hadNotifyHostReady(false),
  42. localExportSlots(nullptr),
  43. moduleId(InvalidModuleIndex),
  44. localSlotCount(InvalidSlotCount),
  45. promise(nullptr),
  46. localExportCount(0)
  47. {
  48. namespaceRecord.module = this;
  49. namespaceRecord.bindingName = PropertyIds::star_;
  50. }
  51. SourceTextModuleRecord* SourceTextModuleRecord::Create(ScriptContext* scriptContext)
  52. {
  53. Recycler* recycler = scriptContext->GetRecycler();
  54. SourceTextModuleRecord* childModuleRecord;
  55. childModuleRecord = RecyclerNewFinalized(recycler, Js::SourceTextModuleRecord, scriptContext);
  56. // There is no real reference to lifetime management in ecmascript
  57. // The life time of a module record should be controlled by the module registry as defined in WHATWG module loader spec
  58. // in practice the modulerecord lifetime should be the same as the scriptcontext so it could be retrieved for the same
  59. // site. Host might hold a reference to the module as well after initializing the module.
  60. // In our implementation, we'll use the moduleId in bytecode to identify the module.
  61. childModuleRecord->moduleId = scriptContext->GetLibrary()->EnsureModuleRecordList()->Add(childModuleRecord);
  62. return childModuleRecord;
  63. }
  64. void SourceTextModuleRecord::Finalize(bool isShutdown)
  65. {
  66. parseTree = nullptr;
  67. requestedModuleList = nullptr;
  68. importRecordList = nullptr;
  69. localExportRecordList = nullptr;
  70. indirectExportRecordList = nullptr;
  71. starExportRecordList = nullptr;
  72. parentModuleList = nullptr;
  73. if (!isShutdown)
  74. {
  75. AdeleteUnlessNull(scriptContext->GeneralAllocator(), parser);
  76. AdeleteUnlessNull(scriptContext->GeneralAllocator(), childrenModuleSet);
  77. }
  78. }
  79. HRESULT SourceTextModuleRecord::ParseSource(__in_bcount(sourceLength) byte* sourceText, uint32 sourceLength, SRCINFO * srcInfo, Var* exceptionVar, bool isUtf8)
  80. {
  81. Assert(!wasParsed || sourceText == nullptr);
  82. Assert(parser == nullptr);
  83. Assert(exceptionVar != nullptr);
  84. HRESULT hr = NOERROR;
  85. // Return if loading failure has been reported
  86. if (sourceText == nullptr && wasParsed)
  87. {
  88. return hr;
  89. }
  90. ScriptContext* scriptContext = GetScriptContext();
  91. CompileScriptException se;
  92. ArenaAllocator* allocator = scriptContext->GeneralAllocator();
  93. *exceptionVar = nullptr;
  94. if (!scriptContext->GetConfig()->IsES6ModuleEnabled())
  95. {
  96. JavascriptError *pError = scriptContext->GetLibrary()->CreateError();
  97. JavascriptError::SetErrorMessageProperties(pError, hr, _u("ES6Module not supported"), scriptContext);
  98. *exceptionVar = pError;
  99. return E_NOTIMPL;
  100. }
  101. // Host indicates that the current module failed to load.
  102. if (sourceText == nullptr)
  103. {
  104. Assert(sourceLength == 0);
  105. OUTPUT_TRACE_DEBUGONLY(Js::ModulePhase, _u("Failed to load: %s\n"), this->GetSpecifierSz());
  106. hr = E_FAIL;
  107. // We cannot just use the buffer in the specifier string - need to make a copy here.
  108. const char16* moduleName = this->GetSpecifierSz();
  109. size_t length = wcslen(moduleName);
  110. char16* allocatedString = RecyclerNewArrayLeaf(scriptContext->GetRecycler(), char16, length + 1);
  111. wmemcpy_s(allocatedString, length + 1, moduleName, length);
  112. allocatedString[length] = _u('\0');
  113. JavascriptError *pError = scriptContext->GetLibrary()->CreateURIError();
  114. JavascriptError::SetErrorMessageProperties(pError, hr, allocatedString, scriptContext);
  115. *exceptionVar = pError;
  116. }
  117. else
  118. {
  119. OUTPUT_TRACE_DEBUGONLY(Js::ModulePhase, _u("ParseSource(%s)\n"), this->GetSpecifierSz());
  120. try
  121. {
  122. AUTO_NESTED_HANDLED_EXCEPTION_TYPE((ExceptionType)(ExceptionType_OutOfMemory | ExceptionType_StackOverflow));
  123. this->parser = Anew(allocator, Parser, scriptContext);
  124. srcInfo->moduleID = moduleId;
  125. LoadScriptFlag loadScriptFlag = (LoadScriptFlag)(LoadScriptFlag_Expression | LoadScriptFlag_Module |
  126. LoadScriptFlag_disableAsmJs | (isUtf8 ? LoadScriptFlag_Utf8Source : LoadScriptFlag_None));
  127. Utf8SourceInfo* pResultSourceInfo = nullptr;
  128. this->parseTree = scriptContext->ParseScript(parser, sourceText,
  129. sourceLength, srcInfo, &se, &pResultSourceInfo, _u("module"),
  130. loadScriptFlag, &sourceIndex, nullptr);
  131. this->pSourceInfo = pResultSourceInfo;
  132. }
  133. catch (Js::OutOfMemoryException)
  134. {
  135. hr = E_OUTOFMEMORY;
  136. }
  137. catch (Js::StackOverflowException)
  138. {
  139. hr = VBSERR_OutOfStack;
  140. }
  141. if (FAILED(hr))
  142. {
  143. se.ProcessError(nullptr, hr, nullptr);
  144. }
  145. else if (parseTree == nullptr)
  146. {
  147. hr = E_FAIL;
  148. }
  149. else
  150. {
  151. hr = PostParseProcess();
  152. if (hr == S_OK && this->errorObject != nullptr && this->hadNotifyHostReady)
  153. {
  154. // This would be the case where the child module got error and current module has notified error already.
  155. if (*exceptionVar == nullptr)
  156. {
  157. *exceptionVar = this->errorObject;
  158. }
  159. // Cleanup in case of error.
  160. this->ReleaseParserResources();
  161. return E_FAIL;
  162. }
  163. }
  164. }
  165. if (FAILED(hr))
  166. {
  167. if (*exceptionVar == nullptr)
  168. {
  169. const WCHAR * sourceUrl = nullptr;
  170. if (this->GetModuleUrl())
  171. {
  172. sourceUrl = this->GetModuleUrlSz();
  173. }
  174. *exceptionVar = JavascriptError::CreateFromCompileScriptException(scriptContext, &se, sourceUrl);
  175. }
  176. if (this->parser)
  177. {
  178. this->parseTree = nullptr;
  179. Adelete(allocator, this->parser);
  180. this->parser = nullptr;
  181. }
  182. if (this->errorObject == nullptr)
  183. {
  184. this->errorObject = *exceptionVar;
  185. }
  186. if (this->promise != nullptr)
  187. {
  188. SourceTextModuleRecord::ResolveOrRejectDynamicImportPromise(false, this->errorObject, this->scriptContext, this);
  189. }
  190. // Notify host if current module is dynamically-loaded module, or is root module and the host hasn't been notified
  191. if (this->promise != nullptr || (isRootModule && !hadNotifyHostReady))
  192. {
  193. OUTPUT_TRACE_DEBUGONLY(Js::ModulePhase, _u("\t>NotifyHostAboutModuleReady %s (ParseSource error)\n"), this->GetSpecifierSz());
  194. LEAVE_SCRIPT_IF_ACTIVE(scriptContext,
  195. {
  196. scriptContext->GetHostScriptContext()->NotifyHostAboutModuleReady(this, this->errorObject);
  197. });
  198. hadNotifyHostReady = true;
  199. }
  200. // Notify parent if applicable
  201. OUTPUT_TRACE_DEBUGONLY(Js::ModulePhase, _u("\t>NotifyParentAsNeeded\n"));
  202. NotifyParentsAsNeeded();
  203. }
  204. return hr;
  205. }
  206. void SourceTextModuleRecord::NotifyParentsAsNeeded()
  207. {
  208. if (notifying)
  209. {
  210. return;
  211. }
  212. notifying = true;
  213. // Notify the parent modules that this child module is either in fault state or finished.
  214. if (this->parentModuleList != nullptr)
  215. {
  216. parentModuleList->Map([=](uint i, SourceTextModuleRecord* parentModule)
  217. {
  218. parentModule->OnChildModuleReady(this, this->errorObject);
  219. });
  220. }
  221. notifying = false;
  222. SetParentsNotified();
  223. }
  224. void SourceTextModuleRecord::ImportModuleListsFromParser()
  225. {
  226. Assert(scriptContext->GetConfig()->IsES6ModuleEnabled());
  227. ParseNodeModule* moduleParseNode = this->parseTree->AsParseNodeModule();
  228. SetrequestedModuleList(moduleParseNode->requestedModules);
  229. SetImportRecordList(moduleParseNode->importEntries);
  230. SetStarExportRecordList(moduleParseNode->starExportEntries);
  231. SetIndirectExportRecordList(moduleParseNode->indirectExportEntries);
  232. SetLocalExportRecordList(moduleParseNode->localExportEntries);
  233. }
  234. void SourceTextModuleRecord::ReleaseParserResources()
  235. {
  236. if (this->parser != nullptr)
  237. {
  238. this->parser->ReleaseTemporaryGuestArena();
  239. }
  240. }
  241. HRESULT SourceTextModuleRecord::PostParseProcess()
  242. {
  243. HRESULT hr = NOERROR;
  244. SetWasParsed();
  245. ImportModuleListsFromParser();
  246. hr = ResolveExternalModuleDependencies();
  247. if (SUCCEEDED(hr))
  248. {
  249. hr = PrepareForModuleDeclarationInitialization();
  250. }
  251. else
  252. {
  253. // Cleanup in case of error.
  254. this->ReleaseParserResources();
  255. }
  256. return hr;
  257. }
  258. Var SourceTextModuleRecord::PostProcessDynamicModuleImport()
  259. {
  260. JavascriptPromise *promise = this->GetPromise();
  261. ScriptContext* scriptContext = GetScriptContext();
  262. AnalysisAssert(scriptContext != nullptr);
  263. if (promise == nullptr)
  264. {
  265. promise = JavascriptPromise::CreateEnginePromise(scriptContext);
  266. this->SetPromise(promise);
  267. }
  268. if (this->ParentsNotified())
  269. {
  270. HRESULT hr = NOERROR;
  271. if (!WasDeclarationInitialized())
  272. {
  273. if (ModuleDeclarationInstantiation())
  274. {
  275. GenerateRootFunction();
  276. }
  277. if (this->errorObject != nullptr)
  278. {
  279. // Cleanup in case of error.
  280. this->ReleaseParserResources();
  281. SourceTextModuleRecord::ResolveOrRejectDynamicImportPromise(false, this->errorObject, scriptContext, this);
  282. }
  283. else
  284. {
  285. if (!hadNotifyHostReady && !WasEvaluated())
  286. {
  287. OUTPUT_TRACE_DEBUGONLY(Js::ModulePhase, _u("\t>NotifyHostAboutModuleReady %s (PostProcessDynamicModuleImport)\n"), this->GetSpecifierSz());
  288. LEAVE_SCRIPT_IF_ACTIVE(scriptContext,
  289. {
  290. hr = scriptContext->GetHostScriptContext()->NotifyHostAboutModuleReady(this, this->errorObject);
  291. });
  292. hadNotifyHostReady = true;
  293. }
  294. }
  295. }
  296. if (FAILED(hr))
  297. {
  298. // Cleanup in case of error.
  299. this->ReleaseParserResources();
  300. // We cannot just use the buffer in the specifier string - need to make a copy here.
  301. const char16* moduleName = this->GetSpecifierSz();
  302. size_t length = wcslen(moduleName);
  303. char16* allocatedString = RecyclerNewArrayLeaf(scriptContext->GetRecycler(), char16, length + 1);
  304. wmemcpy_s(allocatedString, length + 1, moduleName, length);
  305. allocatedString[length] = _u('\0');
  306. Js::JavascriptError * error = scriptContext->GetLibrary()->CreateURIError();
  307. JavascriptError::SetErrorMessageProperties(error, hr, allocatedString, scriptContext);
  308. return SourceTextModuleRecord::ResolveOrRejectDynamicImportPromise(false, error, scriptContext, this);
  309. }
  310. }
  311. return this->promise;
  312. }
  313. HRESULT SourceTextModuleRecord::PrepareForModuleDeclarationInitialization()
  314. {
  315. OUTPUT_TRACE_DEBUGONLY(Js::ModulePhase, _u("PrepareForModuleDeclarationInitialization(%s)\n"), this->GetSpecifierSz());
  316. HRESULT hr = NO_ERROR;
  317. if (ConfirmChildrenParsed())
  318. {
  319. OUTPUT_TRACE_DEBUGONLY(Js::ModulePhase, _u("\t>NotifyParentsAsNeeded\n"));
  320. NotifyParentsAsNeeded();
  321. if (!WasDeclarationInitialized() && (isRootModule || this->promise != nullptr))
  322. {
  323. // TODO: move this as a promise call? if parser is called from a different thread
  324. // We'll need to call the bytecode gen in the main thread as we are accessing GC.
  325. ScriptContext* scriptContext = GetScriptContext();
  326. Assert(!scriptContext->GetThreadContext()->IsScriptActive() || this->promise != nullptr);
  327. if (ModuleDeclarationInstantiation())
  328. {
  329. GenerateRootFunction();
  330. }
  331. if (!hadNotifyHostReady && !WasEvaluated())
  332. {
  333. OUTPUT_TRACE_DEBUGONLY(Js::ModulePhase, _u("\t>NotifyHostAboutModuleReady %s (PrepareForModuleDeclarationInitialization)\n"), this->GetSpecifierSz());
  334. LEAVE_SCRIPT_IF_ACTIVE(scriptContext,
  335. {
  336. hr = scriptContext->GetHostScriptContext()->NotifyHostAboutModuleReady(this, this->errorObject);
  337. });
  338. hadNotifyHostReady = true;
  339. }
  340. }
  341. }
  342. return hr;
  343. }
  344. HRESULT SourceTextModuleRecord::OnChildModuleReady(SourceTextModuleRecord* childModule, Var childException)
  345. {
  346. OUTPUT_TRACE_DEBUGONLY(Js::ModulePhase, _u("OnChildModuleReady(%s)\n"), this->GetSpecifierSz(), childModule->GetSpecifierSz());
  347. HRESULT hr = NOERROR;
  348. if (childException != nullptr)
  349. {
  350. // propagate the error up as needed.
  351. if (this->errorObject == nullptr)
  352. {
  353. this->errorObject = childException;
  354. }
  355. // Cleanup in case of error.
  356. this->ReleaseParserResources();
  357. OUTPUT_TRACE_DEBUGONLY(Js::ModulePhase, _u("\t>NotifyParentAsNeeded (childException)\n"), this->GetSpecifierSz());
  358. NotifyParentsAsNeeded();
  359. if (this->promise != nullptr)
  360. {
  361. SourceTextModuleRecord::ResolveOrRejectDynamicImportPromise(false, this->errorObject, this->scriptContext, this);
  362. }
  363. if (this->promise != nullptr || (isRootModule && !hadNotifyHostReady))
  364. {
  365. OUTPUT_TRACE_DEBUGONLY(Js::ModulePhase, _u("\t>NotifyHostAboutModuleReady %s (OnChildModuleReady)\n"), this->GetSpecifierSz());
  366. LEAVE_SCRIPT_IF_ACTIVE(scriptContext,
  367. {
  368. hr = scriptContext->GetHostScriptContext()->NotifyHostAboutModuleReady(this, this->errorObject);
  369. });
  370. hadNotifyHostReady = true;
  371. }
  372. }
  373. else
  374. {
  375. hr = PrepareForModuleDeclarationInitialization();
  376. }
  377. return hr;
  378. }
  379. ModuleNamespace* SourceTextModuleRecord::GetNamespace()
  380. {
  381. Assert(localExportSlots != nullptr);
  382. Assert(PointerValue(localExportSlots[GetLocalExportSlotCount()]) == __super::GetNamespace());
  383. return (ModuleNamespace*)(void*)(localExportSlots[GetLocalExportSlotCount()]);
  384. }
  385. void SourceTextModuleRecord::SetNamespace(ModuleNamespace* moduleNamespace)
  386. {
  387. Assert(localExportSlots != nullptr);
  388. __super::SetNamespace(moduleNamespace);
  389. localExportSlots[GetLocalExportSlotCount()] = moduleNamespace;
  390. }
  391. ExportedNames* SourceTextModuleRecord::GetExportedNames(ExportModuleRecordList* exportStarSet)
  392. {
  393. const bool isRootGetExportedNames = (exportStarSet == nullptr);
  394. // this->exportedNames only caches root "GetExportedNames(nullptr)"
  395. if (isRootGetExportedNames && exportedNames != nullptr)
  396. {
  397. return exportedNames;
  398. }
  399. ArenaAllocator* allocator = scriptContext->GeneralAllocator();
  400. if (exportStarSet == nullptr)
  401. {
  402. exportStarSet = Anew(allocator, ExportModuleRecordList, allocator);
  403. }
  404. if (exportStarSet->Has(this))
  405. {
  406. return nullptr;
  407. }
  408. exportStarSet->Prepend(this);
  409. ExportedNames* tempExportedNames = nullptr;
  410. if (this->localExportRecordList != nullptr)
  411. {
  412. tempExportedNames = Anew(allocator, ExportedNames, allocator);
  413. this->localExportRecordList->Map([=](ModuleImportOrExportEntry exportEntry) {
  414. PropertyId exportNameId = EnsurePropertyIdForIdentifier(exportEntry.exportName);
  415. tempExportedNames->Prepend(exportNameId);
  416. });
  417. }
  418. if (this->indirectExportRecordList != nullptr)
  419. {
  420. if (tempExportedNames == nullptr)
  421. {
  422. tempExportedNames = Anew(allocator, ExportedNames, allocator);
  423. }
  424. this->indirectExportRecordList->Map([=](ModuleImportOrExportEntry exportEntry) {
  425. PropertyId exportedNameId = EnsurePropertyIdForIdentifier(exportEntry.exportName);
  426. tempExportedNames->Prepend(exportedNameId);
  427. });
  428. }
  429. if (this->starExportRecordList != nullptr)
  430. {
  431. if (tempExportedNames == nullptr)
  432. {
  433. tempExportedNames = Anew(allocator, ExportedNames, allocator);
  434. }
  435. this->starExportRecordList->Map([=](ModuleImportOrExportEntry exportEntry) {
  436. Assert(exportEntry.moduleRequest != nullptr);
  437. SourceTextModuleRecord* moduleRecord = nullptr;
  438. if (this->childrenModuleSet->TryGetValue(exportEntry.moduleRequest->Psz(), &moduleRecord))
  439. {
  440. Assert(moduleRecord->WasParsed());
  441. Assert(moduleRecord->WasDeclarationInitialized()); // we should be half way during initialization
  442. Assert(!moduleRecord->WasEvaluated());
  443. ExportedNames* starExportedNames = moduleRecord->GetExportedNames(exportStarSet);
  444. // We are not rejecting ambiguous resolution at this time.
  445. if (starExportedNames != nullptr)
  446. {
  447. starExportedNames->Map([&](PropertyId propertyId) {
  448. if (propertyId != PropertyIds::default_ && !tempExportedNames->Has(propertyId))
  449. {
  450. tempExportedNames->Prepend(propertyId);
  451. }
  452. });
  453. }
  454. }
  455. #if DBG
  456. else
  457. {
  458. AssertMsg(false, "dependent modules should have been initialized");
  459. }
  460. #endif
  461. });
  462. }
  463. // this->exportedNames only caches root "GetExportedNames(nullptr)"
  464. if (isRootGetExportedNames)
  465. {
  466. exportedNames = tempExportedNames;
  467. }
  468. return tempExportedNames;
  469. }
  470. bool SourceTextModuleRecord::ResolveImport(PropertyId localName, ModuleNameRecord** importRecord)
  471. {
  472. *importRecord = nullptr;
  473. importRecordList->MapUntil([&](ModuleImportOrExportEntry& importEntry) {
  474. Js::PropertyId localNamePid = EnsurePropertyIdForIdentifier(importEntry.localName);
  475. if (localNamePid == localName)
  476. {
  477. SourceTextModuleRecord* childModule = this->GetChildModuleRecord(importEntry.moduleRequest->Psz());
  478. Js::PropertyId importName = EnsurePropertyIdForIdentifier(importEntry.importName);
  479. if (importName == Js::PropertyIds::star_)
  480. {
  481. *importRecord = childModule->GetNamespaceNameRecord();
  482. }
  483. else
  484. {
  485. childModule->ResolveExport(importName, nullptr, importRecord);
  486. }
  487. return true;
  488. }
  489. return false;
  490. });
  491. return *importRecord != nullptr;
  492. }
  493. // return false when "ambiguous".
  494. // otherwise nullptr means "null" where we have circular reference/cannot resolve.
  495. bool SourceTextModuleRecord::ResolveExport(PropertyId exportName, ResolveSet* resolveSet, ModuleNameRecord** exportRecord)
  496. {
  497. ArenaAllocator* allocator = scriptContext->GeneralAllocator();
  498. if (resolvedExportMap == nullptr)
  499. {
  500. resolvedExportMap = Anew(allocator, ResolvedExportMap, allocator);
  501. }
  502. if (resolvedExportMap->TryGetReference(exportName, exportRecord))
  503. {
  504. return true;
  505. }
  506. // TODO: use per-call/loop allocator?
  507. if (resolveSet == nullptr)
  508. {
  509. resolveSet = Anew(allocator, ResolveSet, allocator);
  510. }
  511. *exportRecord = nullptr;
  512. bool hasCircularRef = false;
  513. resolveSet->MapUntil([&](ModuleNameRecord moduleNameRecord) {
  514. if (moduleNameRecord.module == this && moduleNameRecord.bindingName == exportName)
  515. {
  516. *exportRecord = nullptr;
  517. hasCircularRef = true;
  518. return true;
  519. }
  520. return false;
  521. });
  522. if (hasCircularRef)
  523. {
  524. Assert(*exportRecord == nullptr);
  525. return true;
  526. }
  527. resolveSet->Prepend(ModuleNameRecord(this, exportName));
  528. if (localExportRecordList != nullptr)
  529. {
  530. PropertyId localNameId = Js::Constants::NoProperty;
  531. localExportRecordList->MapUntil([&](ModuleImportOrExportEntry exportEntry) {
  532. PropertyId exportNameId = EnsurePropertyIdForIdentifier(exportEntry.exportName);
  533. if (exportNameId == exportName)
  534. {
  535. localNameId = EnsurePropertyIdForIdentifier(exportEntry.localName);
  536. return true;
  537. }
  538. return false;
  539. });
  540. if (localNameId != Js::Constants::NoProperty)
  541. {
  542. // Check to see if we are exporting something we imported from another module without using a re-export.
  543. // ex: import { foo } from 'module'; export { foo };
  544. ModuleRecordBase* sourceModule = this;
  545. ModuleNameRecord* importRecord = nullptr;
  546. if (this->importRecordList != nullptr
  547. && this->ResolveImport(localNameId, &importRecord)
  548. && importRecord != nullptr)
  549. {
  550. sourceModule = importRecord->module;
  551. localNameId = importRecord->bindingName;
  552. }
  553. resolvedExportMap->AddNew(exportName, { sourceModule, localNameId });
  554. // return the address from Map buffer.
  555. resolvedExportMap->TryGetReference(exportName, exportRecord);
  556. return true;
  557. }
  558. }
  559. if (indirectExportRecordList != nullptr)
  560. {
  561. bool isAmbiguous = false;
  562. indirectExportRecordList->MapUntil([&](ModuleImportOrExportEntry exportEntry) {
  563. PropertyId reexportNameId = EnsurePropertyIdForIdentifier(exportEntry.exportName);
  564. if (exportName != reexportNameId)
  565. {
  566. return false;
  567. }
  568. PropertyId importNameId = EnsurePropertyIdForIdentifier(exportEntry.importName);
  569. SourceTextModuleRecord* childModuleRecord = GetChildModuleRecord(exportEntry.moduleRequest->Psz());
  570. if (childModuleRecord == nullptr)
  571. {
  572. JavascriptError::ThrowReferenceError(scriptContext, JSERR_CannotResolveModule, exportEntry.moduleRequest->Psz());
  573. }
  574. if (exportEntry.importName->GetPropertyId() == PropertyIds::star_)
  575. {
  576. // export * as someName from "foo"
  577. *exportRecord = childModuleRecord->GetNamespaceNameRecord();
  578. return true;
  579. }
  580. isAmbiguous = !childModuleRecord->ResolveExport(importNameId, resolveSet, exportRecord);
  581. if (isAmbiguous)
  582. {
  583. // ambiguous; don't need to search further
  584. return true;
  585. }
  586. // found a resolution. done;
  587. if (*exportRecord != nullptr)
  588. {
  589. return true;
  590. }
  591. return false;
  592. });
  593. if (isAmbiguous)
  594. {
  595. return false;
  596. }
  597. if (*exportRecord != nullptr)
  598. {
  599. return true;
  600. }
  601. }
  602. if (exportName == PropertyIds::default_)
  603. {
  604. JavascriptError* errorObj = scriptContext->GetLibrary()->CreateSyntaxError();
  605. JavascriptError::SetErrorMessage(errorObj, JSERR_ModuleResolveExport, scriptContext->GetPropertyName(exportName)->GetBuffer(), scriptContext);
  606. this->errorObject = errorObj;
  607. return false;
  608. }
  609. bool ambiguousResolution = false;
  610. if (this->starExportRecordList != nullptr)
  611. {
  612. ModuleNameRecord* starResolution = nullptr;
  613. starExportRecordList->MapUntil([&](ModuleImportOrExportEntry starExportEntry) {
  614. ModuleNameRecord* currentResolution = nullptr;
  615. SourceTextModuleRecord* childModule = GetChildModuleRecord(starExportEntry.moduleRequest->Psz());
  616. if (childModule == nullptr)
  617. {
  618. JavascriptError::ThrowReferenceError(GetScriptContext(), JSERR_CannotResolveModule, starExportEntry.moduleRequest->Psz());
  619. }
  620. if (childModule->errorObject != nullptr)
  621. {
  622. JavascriptExceptionOperators::Throw(childModule->errorObject, GetScriptContext());
  623. }
  624. // if ambiguous, return "ambiguous"
  625. if (!childModule->ResolveExport(exportName, resolveSet, &currentResolution))
  626. {
  627. ambiguousResolution = true;
  628. return true;
  629. }
  630. if (currentResolution != nullptr)
  631. {
  632. if (starResolution == nullptr)
  633. {
  634. starResolution = currentResolution;
  635. }
  636. else
  637. {
  638. if (currentResolution->bindingName != starResolution->bindingName ||
  639. currentResolution->module != starResolution->module)
  640. {
  641. ambiguousResolution = true;
  642. }
  643. return true;
  644. }
  645. }
  646. return false;
  647. });
  648. if (!ambiguousResolution)
  649. {
  650. *exportRecord = starResolution;
  651. }
  652. }
  653. return !ambiguousResolution;
  654. }
  655. void SourceTextModuleRecord::SetParent(SourceTextModuleRecord* parentRecord, LPCOLESTR moduleName)
  656. {
  657. Assert(parentRecord != nullptr);
  658. parentRecord->EnsureChildModuleSet(GetScriptContext());
  659. if (!parentRecord->childrenModuleSet->ContainsKey(moduleName))
  660. {
  661. parentRecord->childrenModuleSet->AddNew(moduleName, this);
  662. if (this->parentModuleList == nullptr)
  663. {
  664. Recycler* recycler = GetScriptContext()->GetRecycler();
  665. this->parentModuleList = RecyclerNew(recycler, ModuleRecordList, recycler);
  666. }
  667. if (!this->parentModuleList->Contains(parentRecord))
  668. {
  669. this->parentModuleList->Add(parentRecord);
  670. }
  671. }
  672. }
  673. bool SourceTextModuleRecord::ConfirmChildrenParsed()
  674. {
  675. if (!this->WasParsed())
  676. {
  677. return false;
  678. }
  679. if (confirmedReady || this->ParentsNotified())
  680. {
  681. return true;
  682. }
  683. bool result = true;
  684. confirmedReady = true;
  685. EnsureChildModuleSet(GetScriptContext());
  686. childrenModuleSet->EachValue([&](SourceTextModuleRecord* childModuleRecord) {
  687. if (childModuleRecord->ParentsNotified())
  688. {
  689. return false;
  690. }
  691. else
  692. {
  693. if (childModuleRecord->ConfirmChildrenParsed())
  694. {
  695. return false;
  696. }
  697. else
  698. {
  699. result = false;
  700. return true;
  701. }
  702. }
  703. });
  704. confirmedReady = false;
  705. return result;
  706. }
  707. void SourceTextModuleRecord::EnsureChildModuleSet(ScriptContext *scriptContext)
  708. {
  709. if (nullptr == this->childrenModuleSet)
  710. {
  711. ArenaAllocator* allocator = scriptContext->GeneralAllocator();
  712. this->childrenModuleSet = Anew(allocator, ChildModuleRecordSet, allocator);
  713. }
  714. }
  715. HRESULT SourceTextModuleRecord::ResolveExternalModuleDependencies()
  716. {
  717. OUTPUT_TRACE_DEBUGONLY(Js::ModulePhase, _u("ResolveExternalModuleDependencies(%s)\n"), this->GetSpecifierSz());
  718. ScriptContext* scriptContext = GetScriptContext();
  719. HRESULT hr = NOERROR;
  720. if (requestedModuleList != nullptr)
  721. {
  722. EnsureChildModuleSet(scriptContext);
  723. requestedModuleList->MapUntil([&](IdentPtr specifier) {
  724. LPCOLESTR moduleName = specifier->Psz();
  725. ModuleRecordBase* moduleRecordBase = nullptr;
  726. SourceTextModuleRecord* moduleRecord = nullptr;
  727. bool itemFound = childrenModuleSet->TryGetValue(moduleName, &moduleRecord);
  728. if (!itemFound)
  729. {
  730. hr = scriptContext->GetHostScriptContext()->FetchImportedModule(this, moduleName, &moduleRecordBase);
  731. if (FAILED(hr))
  732. {
  733. return true;
  734. }
  735. moduleRecord = SourceTextModuleRecord::FromHost(moduleRecordBase);
  736. Var errorObject = moduleRecord->GetErrorObject();
  737. if (errorObject == nullptr)
  738. {
  739. OUTPUT_TRACE_DEBUGONLY(Js::ModulePhase, _u("\t>SetParent in (%s)\n"), moduleRecord->GetSpecifierSz());
  740. moduleRecord->SetParent(this, moduleName);
  741. }
  742. else
  743. {
  744. this->errorObject = errorObject;
  745. hr = E_FAIL;
  746. return true;
  747. }
  748. }
  749. return false;
  750. });
  751. if (FAILED(hr))
  752. {
  753. if (this->errorObject == nullptr)
  754. {
  755. JavascriptError *error = scriptContext->GetLibrary()->CreateError();
  756. JavascriptError::SetErrorMessageProperties(error, hr, _u("fetch import module failed"), scriptContext);
  757. this->errorObject = error;
  758. }
  759. OUTPUT_TRACE_DEBUGONLY(Js::ModulePhase, _u("\tfetch import module failed\n"));
  760. NotifyParentsAsNeeded();
  761. }
  762. }
  763. return hr;
  764. }
  765. void SourceTextModuleRecord::CleanupBeforeExecution()
  766. {
  767. // zero out fields is more a defense in depth as those fields are not needed anymore
  768. Assert(wasParsed);
  769. Assert(wasEvaluated);
  770. Assert(wasDeclarationInitialized);
  771. // Debugger can reparse the source and generate the byte code again. Don't cleanup the
  772. // helper information for now.
  773. // Parser uses a temporary guest arena to keep regex patterns alive. We need to release this arena only after we have no further use
  774. // for the regex pattern objects.
  775. this->ReleaseParserResources();
  776. }
  777. bool SourceTextModuleRecord::ModuleDeclarationInstantiation()
  778. {
  779. OUTPUT_TRACE_DEBUGONLY(Js::ModulePhase, _u("ModuleDeclarationInstantiation(%s)\n"), this->GetSpecifierSz());
  780. ScriptContext* scriptContext = GetScriptContext();
  781. if (this->WasDeclarationInitialized() || this->errorObject != nullptr)
  782. {
  783. return false;
  784. }
  785. try
  786. {
  787. AUTO_NESTED_HANDLED_EXCEPTION_TYPE((ExceptionType)(ExceptionType_OutOfMemory|ExceptionType_JavascriptException));
  788. InitializeLocalExports();
  789. InitializeLocalImports();
  790. InitializeIndirectExports();
  791. SetWasDeclarationInitialized();
  792. if (childrenModuleSet != nullptr)
  793. {
  794. childrenModuleSet->EachValue([=](SourceTextModuleRecord* childModuleRecord)
  795. {
  796. Assert(childModuleRecord->WasParsed());
  797. childModuleRecord->ModuleDeclarationInstantiation();
  798. });
  799. }
  800. ENTER_SCRIPT_IF(scriptContext, true, false, false, !scriptContext->GetThreadContext()->IsScriptActive(),
  801. {
  802. ModuleNamespace::GetModuleNamespace(this);
  803. });
  804. }
  805. catch (const JavascriptException& err)
  806. {
  807. this->errorObject = err.GetAndClear()->GetThrownObject(scriptContext);
  808. }
  809. if (this->errorObject != nullptr)
  810. {
  811. OUTPUT_TRACE_DEBUGONLY(Js::ModulePhase, _u("\t>NotifyParentsAsNeeded (errorObject)\n"));
  812. // Cleanup in case of error.
  813. this->ReleaseParserResources();
  814. NotifyParentsAsNeeded();
  815. return false;
  816. }
  817. return true;
  818. }
  819. void SourceTextModuleRecord::GenerateRootFunction()
  820. {
  821. // On cyclic dependency, we may endup generating the root function twice
  822. // so make sure we don't
  823. if (this->rootFunction != nullptr)
  824. {
  825. return;
  826. }
  827. ScriptContext* scriptContext = GetScriptContext();
  828. Js::AutoDynamicCodeReference dynamicFunctionReference(scriptContext);
  829. CompileScriptException se;
  830. Assert(this->WasDeclarationInitialized());
  831. Assert(this == scriptContext->GetLibrary()->GetModuleRecord(this->pSourceInfo->GetSrcInfo()->moduleID));
  832. this->rootFunction = scriptContext->GenerateRootFunction(parseTree, sourceIndex, this->parser, this->pSourceInfo->GetParseFlags(), &se, _u("module"));
  833. if (rootFunction == nullptr)
  834. {
  835. const WCHAR * sourceUrl = nullptr;
  836. if (this->GetModuleUrl())
  837. {
  838. sourceUrl = this->GetModuleUrlSz();
  839. }
  840. this->errorObject = JavascriptError::CreateFromCompileScriptException(scriptContext, &se, sourceUrl);
  841. OUTPUT_TRACE_DEBUGONLY(Js::ModulePhase, _u("\t>NotifyParentAsNeeded rootFunction == nullptr\n"));
  842. NotifyParentsAsNeeded();
  843. }
  844. #ifdef ENABLE_SCRIPT_DEBUGGING
  845. else
  846. {
  847. scriptContext->GetDebugContext()->RegisterFunction(this->rootFunction->GetFunctionBody(), nullptr);
  848. }
  849. #endif
  850. if (childrenModuleSet != nullptr)
  851. {
  852. childrenModuleSet->EachValue([=](SourceTextModuleRecord* childModuleRecord)
  853. {
  854. childModuleRecord->GenerateRootFunction();
  855. });
  856. }
  857. }
  858. Var SourceTextModuleRecord::ModuleEvaluation()
  859. {
  860. OUTPUT_TRACE_DEBUGONLY(Js::ModulePhase, _u("ModuleEvaluation(%s)\n"), this->GetSpecifierSz());
  861. if (!scriptContext->GetConfig()->IsES6ModuleEnabled() || WasEvaluated())
  862. {
  863. return nullptr;
  864. }
  865. if (this->errorObject != nullptr)
  866. {
  867. // Cleanup in case of error.
  868. this->ReleaseParserResources();
  869. if (this->promise != nullptr)
  870. {
  871. SourceTextModuleRecord::ResolveOrRejectDynamicImportPromise(false, this->errorObject, this->scriptContext, this);
  872. return scriptContext->GetLibrary()->GetUndefined();
  873. }
  874. else
  875. {
  876. JavascriptExceptionOperators::Throw(errorObject, this->scriptContext);
  877. }
  878. }
  879. #if DBG
  880. if (childrenModuleSet != nullptr)
  881. {
  882. childrenModuleSet->EachValue([=](SourceTextModuleRecord* childModuleRecord)
  883. {
  884. AssertMsg(childModuleRecord->WasParsed(), "child module needs to have been parsed");
  885. AssertMsg(childModuleRecord->WasDeclarationInitialized(), "child module needs to have been initialized.");
  886. });
  887. }
  888. #endif
  889. Assert(this->errorObject == nullptr);
  890. SetWasEvaluated();
  891. JavascriptExceptionObject *exception = nullptr;
  892. Var ret = nullptr;
  893. try
  894. {
  895. if (childrenModuleSet != nullptr)
  896. {
  897. childrenModuleSet->EachValue([=](SourceTextModuleRecord* childModuleRecord)
  898. {
  899. if (!childModuleRecord->WasEvaluated())
  900. {
  901. childModuleRecord->ModuleEvaluation();
  902. }
  903. // if child module was evaluated before and threw need to re-throw now
  904. // if child module has been dynamically imported and has exception need to throw
  905. if (childModuleRecord->GetErrorObject() != nullptr)
  906. {
  907. JavascriptExceptionOperators::Throw(childModuleRecord->GetErrorObject(), this->scriptContext);
  908. }
  909. });
  910. }
  911. CleanupBeforeExecution();
  912. Arguments outArgs(CallInfo(CallFlags_Value, 0), nullptr);
  913. AUTO_NESTED_HANDLED_EXCEPTION_TYPE((ExceptionType)(ExceptionType_OutOfMemory | ExceptionType_JavascriptException));
  914. ENTER_SCRIPT_IF(scriptContext, true, false, false, !scriptContext->GetThreadContext()->IsScriptActive(),
  915. {
  916. ret = rootFunction->CallRootFunction(outArgs, scriptContext, true);
  917. });
  918. }
  919. catch (const Js::JavascriptException &err)
  920. {
  921. exception = err.GetAndClear();
  922. Var errorObject = exception->GetThrownObject(scriptContext);
  923. AssertOrFailFastMsg(errorObject != nullptr, "ModuleEvaluation: null error object thrown from root function");
  924. this->errorObject = errorObject;
  925. if (this->promise != nullptr)
  926. {
  927. ResolveOrRejectDynamicImportPromise(false, errorObject, scriptContext, this);
  928. return scriptContext->GetLibrary()->GetUndefined();
  929. }
  930. }
  931. if (exception != nullptr)
  932. {
  933. JavascriptExceptionOperators::DoThrowCheckClone(exception, scriptContext);
  934. }
  935. if (this->promise != nullptr)
  936. {
  937. SourceTextModuleRecord::ResolveOrRejectDynamicImportPromise(true, this->GetNamespace(), this->GetScriptContext(), this);
  938. }
  939. return ret;
  940. }
  941. HRESULT SourceTextModuleRecord::OnHostException(void* errorVar)
  942. {
  943. if (!VarIs<RecyclableObject>(errorVar))
  944. {
  945. return E_INVALIDARG;
  946. }
  947. if (WasParsed())
  948. {
  949. return E_INVALIDARG;
  950. }
  951. this->errorObject = errorVar;
  952. // a sub module failed to download. we need to notify that the parent that sub module failed and we need to report back.
  953. return NOERROR;
  954. }
  955. SourceTextModuleRecord* SourceTextModuleRecord::GetChildModuleRecord(LPCOLESTR specifier) const
  956. {
  957. SourceTextModuleRecord* childModuleRecord = nullptr;
  958. if (childrenModuleSet == nullptr)
  959. {
  960. AssertMsg(false, "We should have some child modulerecords first before trying to get child modulerecord.");
  961. return nullptr;
  962. }
  963. if (!childrenModuleSet->TryGetValue(specifier, &childModuleRecord))
  964. {
  965. return nullptr;
  966. }
  967. return childModuleRecord;
  968. }
  969. void SourceTextModuleRecord::InitializeLocalImports()
  970. {
  971. if (importRecordList != nullptr)
  972. {
  973. importRecordList->Map([&](ModuleImportOrExportEntry& importEntry) {
  974. Js::PropertyId importName = EnsurePropertyIdForIdentifier(importEntry.importName);
  975. SourceTextModuleRecord* childModule = this->GetChildModuleRecord(importEntry.moduleRequest->Psz());
  976. ModuleNameRecord* importRecord = nullptr;
  977. // We don't need to initialize anything for * import.
  978. if (importName != Js::PropertyIds::star_)
  979. {
  980. if (!childModule->ResolveExport(importName, nullptr, &importRecord)
  981. || importRecord == nullptr)
  982. {
  983. JavascriptError* errorObj = scriptContext->GetLibrary()->CreateSyntaxError();
  984. JavascriptError::SetErrorMessage(errorObj, JSERR_ModuleResolveImport, importEntry.importName->Psz(), scriptContext);
  985. this->errorObject = errorObj;
  986. return;
  987. }
  988. }
  989. });
  990. }
  991. }
  992. // Local exports are stored in the slotarray in the SourceTextModuleRecord.
  993. void SourceTextModuleRecord::InitializeLocalExports()
  994. {
  995. Recycler* recycler = scriptContext->GetRecycler();
  996. Var undefineValue = scriptContext->GetLibrary()->GetUndefined();
  997. if (localSlotCount == InvalidSlotCount)
  998. {
  999. uint currentSlotCount = 0;
  1000. if (localExportRecordList != nullptr)
  1001. {
  1002. ArenaAllocator* allocator = scriptContext->GeneralAllocator();
  1003. localExportMapByExportName = Anew(allocator, LocalExportMap, allocator);
  1004. localExportMapByLocalName = Anew(allocator, LocalExportMap, allocator);
  1005. localExportIndexList = Anew(allocator, LocalExportIndexList, allocator);
  1006. localExportRecordList->Map([&](ModuleImportOrExportEntry exportEntry)
  1007. {
  1008. Assert(exportEntry.moduleRequest == nullptr);
  1009. Assert(exportEntry.importName == nullptr);
  1010. PropertyId exportNameId = EnsurePropertyIdForIdentifier(exportEntry.exportName);
  1011. PropertyId localNameId = EnsurePropertyIdForIdentifier(exportEntry.localName);
  1012. // We could have exports that look local but actually exported from other module
  1013. // import {foo} from "module1.js"; export {foo};
  1014. ModuleNameRecord* importRecord = nullptr;
  1015. if (this->GetImportEntryList() != nullptr
  1016. && this->ResolveImport(localNameId, &importRecord)
  1017. && importRecord != nullptr)
  1018. {
  1019. return;
  1020. }
  1021. // 2G is too big already.
  1022. if (localExportCount >= INT_MAX)
  1023. {
  1024. JavascriptError::ThrowRangeError(scriptContext, JSERR_TooManyImportExports);
  1025. }
  1026. localExportCount++;
  1027. uint exportSlot = UINT_MAX;
  1028. for (uint i = 0; i < (uint)localExportIndexList->Count(); i++)
  1029. {
  1030. if (localExportIndexList->Item(i) == localNameId)
  1031. {
  1032. exportSlot = i;
  1033. break;
  1034. }
  1035. }
  1036. if (exportSlot == UINT_MAX)
  1037. {
  1038. exportSlot = currentSlotCount;
  1039. localExportMapByLocalName->Add(localNameId, exportSlot);
  1040. localExportIndexList->Add(localNameId);
  1041. Assert(localExportIndexList->Item(currentSlotCount) == localNameId);
  1042. currentSlotCount++;
  1043. if (currentSlotCount >= INT_MAX)
  1044. {
  1045. JavascriptError::ThrowRangeError(scriptContext, JSERR_TooManyImportExports);
  1046. }
  1047. }
  1048. localExportMapByExportName->Add(exportNameId, exportSlot);
  1049. });
  1050. }
  1051. // Namespace object will be added to the end of the array though invisible through namespace object itself.
  1052. localExportSlots = RecyclerNewArray(recycler, Field(Var), currentSlotCount + 1);
  1053. for (uint i = 0; i < currentSlotCount; i++)
  1054. {
  1055. localExportSlots[i] = undefineValue;
  1056. }
  1057. localExportSlots[currentSlotCount] = nullptr;
  1058. localSlotCount = currentSlotCount;
  1059. #if ENABLE_NATIVE_CODEGEN
  1060. if (JITManager::GetJITManager()->IsOOPJITEnabled() && JITManager::GetJITManager()->IsConnected())
  1061. {
  1062. PSCRIPTCONTEXT_HANDLE remoteScriptContext = this->scriptContext->GetRemoteScriptAddr();
  1063. if (remoteScriptContext)
  1064. {
  1065. HRESULT hr = JITManager::GetJITManager()->AddModuleRecordInfo(
  1066. remoteScriptContext,
  1067. this->GetModuleId(),
  1068. (intptr_t)this->GetLocalExportSlots());
  1069. JITManager::HandleServerCallResult(hr, RemoteCallType::StateUpdate);
  1070. }
  1071. }
  1072. #endif
  1073. }
  1074. }
  1075. PropertyId SourceTextModuleRecord::EnsurePropertyIdForIdentifier(IdentPtr pid)
  1076. {
  1077. PropertyId propertyId = pid->GetPropertyId();
  1078. if (propertyId == Js::Constants::NoProperty)
  1079. {
  1080. propertyId = scriptContext->GetOrAddPropertyIdTracked(pid->Psz(), pid->Cch());
  1081. pid->SetPropertyId(propertyId);
  1082. }
  1083. return propertyId;
  1084. }
  1085. void SourceTextModuleRecord::InitializeIndirectExports()
  1086. {
  1087. ModuleNameRecord* exportRecord = nullptr;
  1088. if (indirectExportRecordList != nullptr)
  1089. {
  1090. indirectExportRecordList->Map([&](ModuleImportOrExportEntry exportEntry)
  1091. {
  1092. PropertyId propertyId = EnsurePropertyIdForIdentifier(exportEntry.importName);
  1093. SourceTextModuleRecord* childModuleRecord = GetChildModuleRecord(exportEntry.moduleRequest->Psz());
  1094. if (childModuleRecord == nullptr)
  1095. {
  1096. JavascriptError* errorObj = scriptContext->GetLibrary()->CreateReferenceError();
  1097. JavascriptError::SetErrorMessage(errorObj, JSERR_CannotResolveModule, exportEntry.moduleRequest->Psz(), scriptContext);
  1098. this->errorObject = errorObj;
  1099. return;
  1100. }
  1101. if (propertyId != PropertyIds::star_ &&
  1102. (!childModuleRecord->ResolveExport(propertyId, nullptr, &exportRecord) ||
  1103. (exportRecord == nullptr)))
  1104. {
  1105. JavascriptError* errorObj = scriptContext->GetLibrary()->CreateSyntaxError();
  1106. JavascriptError::SetErrorMessage(errorObj, JSERR_ModuleResolveExport, exportEntry.exportName->Psz(), scriptContext);
  1107. this->errorObject = errorObj;
  1108. return;
  1109. }
  1110. });
  1111. }
  1112. }
  1113. uint SourceTextModuleRecord::GetLocalExportSlotIndexByExportName(PropertyId exportNameId)
  1114. {
  1115. Assert(localSlotCount != 0);
  1116. Assert(localExportSlots != nullptr);
  1117. uint slotIndex = InvalidSlotIndex;
  1118. if (!localExportMapByExportName->TryGetValue(exportNameId, &slotIndex))
  1119. {
  1120. AssertMsg(false, "exportNameId is not in local export list");
  1121. return InvalidSlotIndex;
  1122. }
  1123. else
  1124. {
  1125. return slotIndex;
  1126. }
  1127. }
  1128. uint SourceTextModuleRecord::GetLocalExportSlotIndexByLocalName(PropertyId localNameId)
  1129. {
  1130. Assert(localSlotCount != 0 || localNameId == PropertyIds::star_);
  1131. Assert(localExportSlots != nullptr);
  1132. uint slotIndex = InvalidSlotIndex;
  1133. if (localNameId == PropertyIds::star_)
  1134. {
  1135. return localSlotCount; // namespace is put on the last slot.
  1136. } else if (!localExportMapByLocalName->TryGetValue(localNameId, &slotIndex))
  1137. {
  1138. AssertMsg(false, "exportNameId is not in local export list");
  1139. return InvalidSlotIndex;
  1140. }
  1141. return slotIndex;
  1142. }
  1143. // static
  1144. Var SourceTextModuleRecord::ResolveOrRejectDynamicImportPromise(bool isResolve, Var value, ScriptContext *scriptContext, SourceTextModuleRecord *moduleRecord)
  1145. {
  1146. bool isScriptActive = scriptContext->GetThreadContext()->IsScriptActive();
  1147. JavascriptPromise *promise = nullptr;
  1148. if (moduleRecord != nullptr)
  1149. {
  1150. promise = moduleRecord->GetPromise();
  1151. }
  1152. if (promise == nullptr)
  1153. {
  1154. promise = JavascriptPromise::CreateEnginePromise(scriptContext);
  1155. }
  1156. ENTER_SCRIPT_IF(scriptContext, true, false, false, !isScriptActive,
  1157. {
  1158. if (isResolve)
  1159. {
  1160. promise->Resolve(value, scriptContext);
  1161. }
  1162. else
  1163. {
  1164. promise->Reject(value, scriptContext);
  1165. }
  1166. });
  1167. if (moduleRecord != nullptr)
  1168. {
  1169. moduleRecord->SetPromise(nullptr);
  1170. }
  1171. return promise;
  1172. }
  1173. }