Interpreter.cpp 158 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670
  1. /*
  2. * Copyright (c) 2021-2024, Andreas Kling <andreas@ladybird.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/HashTable.h>
  8. #include <AK/TemporaryChange.h>
  9. #include <LibJS/AST.h>
  10. #include <LibJS/Bytecode/BasicBlock.h>
  11. #include <LibJS/Bytecode/Generator.h>
  12. #include <LibJS/Bytecode/Instruction.h>
  13. #include <LibJS/Bytecode/Interpreter.h>
  14. #include <LibJS/Bytecode/Label.h>
  15. #include <LibJS/Bytecode/Op.h>
  16. #include <LibJS/Runtime/AbstractOperations.h>
  17. #include <LibJS/Runtime/Accessor.h>
  18. #include <LibJS/Runtime/Array.h>
  19. #include <LibJS/Runtime/BigInt.h>
  20. #include <LibJS/Runtime/DeclarativeEnvironment.h>
  21. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  22. #include <LibJS/Runtime/Environment.h>
  23. #include <LibJS/Runtime/FunctionEnvironment.h>
  24. #include <LibJS/Runtime/GlobalEnvironment.h>
  25. #include <LibJS/Runtime/GlobalObject.h>
  26. #include <LibJS/Runtime/Iterator.h>
  27. #include <LibJS/Runtime/MathObject.h>
  28. #include <LibJS/Runtime/NativeFunction.h>
  29. #include <LibJS/Runtime/ObjectEnvironment.h>
  30. #include <LibJS/Runtime/Realm.h>
  31. #include <LibJS/Runtime/Reference.h>
  32. #include <LibJS/Runtime/RegExpObject.h>
  33. #include <LibJS/Runtime/TypedArray.h>
  34. #include <LibJS/Runtime/Value.h>
  35. #include <LibJS/Runtime/ValueInlines.h>
  36. #include <LibJS/SourceTextModule.h>
  37. namespace JS::Bytecode {
  38. bool g_dump_bytecode = false;
  39. static ByteString format_operand(StringView name, Operand operand, Bytecode::Executable const& executable)
  40. {
  41. StringBuilder builder;
  42. if (!name.is_empty())
  43. builder.appendff("\033[32m{}\033[0m:", name);
  44. switch (operand.type()) {
  45. case Operand::Type::Register:
  46. if (operand.index() == Register::this_value().index()) {
  47. builder.appendff("\033[33mthis\033[0m");
  48. } else {
  49. builder.appendff("\033[33mreg{}\033[0m", operand.index());
  50. }
  51. break;
  52. case Operand::Type::Local:
  53. builder.appendff("\033[34m{}~{}\033[0m", executable.local_variable_names[operand.index() - executable.local_index_base], operand.index() - executable.local_index_base);
  54. break;
  55. case Operand::Type::Constant: {
  56. builder.append("\033[36m"sv);
  57. auto value = executable.constants[operand.index() - executable.number_of_registers];
  58. if (value.is_empty())
  59. builder.append("<Empty>"sv);
  60. else if (value.is_boolean())
  61. builder.appendff("Bool({})", value.as_bool() ? "true"sv : "false"sv);
  62. else if (value.is_int32())
  63. builder.appendff("Int32({})", value.as_i32());
  64. else if (value.is_double())
  65. builder.appendff("Double({})", value.as_double());
  66. else if (value.is_bigint())
  67. builder.appendff("BigInt({})", value.as_bigint().to_byte_string());
  68. else if (value.is_string())
  69. builder.appendff("String(\"{}\")", value.as_string().utf8_string_view());
  70. else if (value.is_undefined())
  71. builder.append("Undefined"sv);
  72. else if (value.is_null())
  73. builder.append("Null"sv);
  74. else
  75. builder.appendff("Value: {}", value);
  76. builder.append("\033[0m"sv);
  77. break;
  78. }
  79. default:
  80. VERIFY_NOT_REACHED();
  81. }
  82. return builder.to_byte_string();
  83. }
  84. static ByteString format_operand_list(StringView name, ReadonlySpan<Operand> operands, Bytecode::Executable const& executable)
  85. {
  86. StringBuilder builder;
  87. if (!name.is_empty())
  88. builder.appendff("\033[32m{}\033[0m:[", name);
  89. for (size_t i = 0; i < operands.size(); ++i) {
  90. if (i != 0)
  91. builder.append(", "sv);
  92. builder.appendff("{}", format_operand(""sv, operands[i], executable));
  93. }
  94. builder.append("]"sv);
  95. return builder.to_byte_string();
  96. }
  97. static ByteString format_value_list(StringView name, ReadonlySpan<Value> values)
  98. {
  99. StringBuilder builder;
  100. if (!name.is_empty())
  101. builder.appendff("\033[32m{}\033[0m:[", name);
  102. builder.join(", "sv, values);
  103. builder.append("]"sv);
  104. return builder.to_byte_string();
  105. }
  106. ALWAYS_INLINE static ThrowCompletionOr<Value> loosely_inequals(VM& vm, Value src1, Value src2)
  107. {
  108. if (src1.tag() == src2.tag()) {
  109. if (src1.is_int32() || src1.is_object() || src1.is_boolean() || src1.is_nullish())
  110. return Value(src1.encoded() != src2.encoded());
  111. }
  112. return Value(!TRY(is_loosely_equal(vm, src1, src2)));
  113. }
  114. ALWAYS_INLINE static ThrowCompletionOr<Value> loosely_equals(VM& vm, Value src1, Value src2)
  115. {
  116. if (src1.tag() == src2.tag()) {
  117. if (src1.is_int32() || src1.is_object() || src1.is_boolean() || src1.is_nullish())
  118. return Value(src1.encoded() == src2.encoded());
  119. }
  120. return Value(TRY(is_loosely_equal(vm, src1, src2)));
  121. }
  122. ALWAYS_INLINE static ThrowCompletionOr<Value> strict_inequals(VM&, Value src1, Value src2)
  123. {
  124. if (src1.tag() == src2.tag()) {
  125. if (src1.is_int32() || src1.is_object() || src1.is_boolean() || src1.is_nullish())
  126. return Value(src1.encoded() != src2.encoded());
  127. }
  128. return Value(!is_strictly_equal(src1, src2));
  129. }
  130. ALWAYS_INLINE static ThrowCompletionOr<Value> strict_equals(VM&, Value src1, Value src2)
  131. {
  132. if (src1.tag() == src2.tag()) {
  133. if (src1.is_int32() || src1.is_object() || src1.is_boolean() || src1.is_nullish())
  134. return Value(src1.encoded() == src2.encoded());
  135. }
  136. return Value(is_strictly_equal(src1, src2));
  137. }
  138. Interpreter::Interpreter(VM& vm)
  139. : m_vm(vm)
  140. {
  141. }
  142. Interpreter::~Interpreter()
  143. {
  144. }
  145. ALWAYS_INLINE Value Interpreter::get(Operand op) const
  146. {
  147. return m_registers_and_constants_and_locals.data()[op.index()];
  148. }
  149. ALWAYS_INLINE void Interpreter::set(Operand op, Value value)
  150. {
  151. m_registers_and_constants_and_locals.data()[op.index()] = value;
  152. }
  153. ALWAYS_INLINE Value Interpreter::do_yield(Value value, Optional<Label> continuation)
  154. {
  155. auto object = Object::create(realm(), nullptr);
  156. object->define_direct_property("result", value, JS::default_attributes);
  157. if (continuation.has_value())
  158. // FIXME: If we get a pointer, which is not accurately representable as a double
  159. // will cause this to explode
  160. object->define_direct_property("continuation", Value(continuation->address()), JS::default_attributes);
  161. else
  162. object->define_direct_property("continuation", js_null(), JS::default_attributes);
  163. object->define_direct_property("isAwait", Value(false), JS::default_attributes);
  164. return object;
  165. }
  166. // 16.1.6 ScriptEvaluation ( scriptRecord ), https://tc39.es/ecma262/#sec-runtime-semantics-scriptevaluation
  167. ThrowCompletionOr<Value> Interpreter::run(Script& script_record)
  168. {
  169. auto& vm = this->vm();
  170. // 1. Let globalEnv be scriptRecord.[[Realm]].[[GlobalEnv]].
  171. auto& global_environment = script_record.realm().global_environment();
  172. // 2. Let scriptContext be a new ECMAScript code execution context.
  173. auto script_context = ExecutionContext::create();
  174. // 3. Set the Function of scriptContext to null.
  175. // NOTE: This was done during execution context construction.
  176. // 4. Set the Realm of scriptContext to scriptRecord.[[Realm]].
  177. script_context->realm = &script_record.realm();
  178. // 5. Set the ScriptOrModule of scriptContext to scriptRecord.
  179. script_context->script_or_module = NonnullGCPtr<Script>(script_record);
  180. // 6. Set the VariableEnvironment of scriptContext to globalEnv.
  181. script_context->variable_environment = &global_environment;
  182. // 7. Set the LexicalEnvironment of scriptContext to globalEnv.
  183. script_context->lexical_environment = &global_environment;
  184. // 8. Set the PrivateEnvironment of scriptContext to null.
  185. // NOTE: This isn't in the spec, but we require it.
  186. script_context->is_strict_mode = script_record.parse_node().is_strict_mode();
  187. // FIXME: 9. Suspend the currently running execution context.
  188. // 10. Push scriptContext onto the execution context stack; scriptContext is now the running execution context.
  189. TRY(vm.push_execution_context(*script_context, {}));
  190. // 11. Let script be scriptRecord.[[ECMAScriptCode]].
  191. auto& script = script_record.parse_node();
  192. // 12. Let result be Completion(GlobalDeclarationInstantiation(script, globalEnv)).
  193. auto instantiation_result = script.global_declaration_instantiation(vm, global_environment);
  194. Completion result = instantiation_result.is_throw_completion() ? instantiation_result.throw_completion() : normal_completion({});
  195. // 13. If result.[[Type]] is normal, then
  196. if (result.type() == Completion::Type::Normal) {
  197. auto executable_result = JS::Bytecode::Generator::generate_from_ast_node(vm, script, {});
  198. if (executable_result.is_error()) {
  199. if (auto error_string = executable_result.error().to_string(); error_string.is_error())
  200. result = vm.template throw_completion<JS::InternalError>(vm.error_message(JS::VM::ErrorMessage::OutOfMemory));
  201. else if (error_string = String::formatted("TODO({})", error_string.value()); error_string.is_error())
  202. result = vm.template throw_completion<JS::InternalError>(vm.error_message(JS::VM::ErrorMessage::OutOfMemory));
  203. else
  204. result = JS::throw_completion(JS::InternalError::create(realm(), error_string.release_value()));
  205. } else {
  206. auto executable = executable_result.release_value();
  207. if (g_dump_bytecode)
  208. executable->dump();
  209. // a. Set result to the result of evaluating script.
  210. auto result_or_error = run_executable(*executable, {}, {});
  211. if (result_or_error.value.is_error())
  212. result = result_or_error.value.release_error();
  213. else
  214. result = result_or_error.return_register_value;
  215. }
  216. }
  217. // 14. If result.[[Type]] is normal and result.[[Value]] is empty, then
  218. if (result.type() == Completion::Type::Normal && !result.value().has_value()) {
  219. // a. Set result to NormalCompletion(undefined).
  220. result = normal_completion(js_undefined());
  221. }
  222. // FIXME: 15. Suspend scriptContext and remove it from the execution context stack.
  223. vm.pop_execution_context();
  224. // 16. Assert: The execution context stack is not empty.
  225. VERIFY(!vm.execution_context_stack().is_empty());
  226. // FIXME: 17. Resume the context that is now on the top of the execution context stack as the running execution context.
  227. // At this point we may have already run any queued promise jobs via on_call_stack_emptied,
  228. // in which case this is a no-op.
  229. // FIXME: These three should be moved out of Interpreter::run and give the host an option to run these, as it's up to the host when these get run.
  230. // https://tc39.es/ecma262/#sec-jobs for jobs and https://tc39.es/ecma262/#_ref_3508 for ClearKeptObjects
  231. // finish_execution_generation is particularly an issue for LibWeb, as the HTML spec wants to run it specifically after performing a microtask checkpoint.
  232. // The promise and registry cleanup queues don't cause LibWeb an issue, as LibWeb overrides the hooks that push onto these queues.
  233. vm.run_queued_promise_jobs();
  234. vm.run_queued_finalization_registry_cleanup_jobs();
  235. vm.finish_execution_generation();
  236. // 18. Return ? result.
  237. if (result.is_abrupt()) {
  238. VERIFY(result.type() == Completion::Type::Throw);
  239. return result.release_error();
  240. }
  241. VERIFY(result.value().has_value());
  242. return *result.value();
  243. }
  244. ThrowCompletionOr<Value> Interpreter::run(SourceTextModule& module)
  245. {
  246. // FIXME: This is not a entry point as defined in the spec, but is convenient.
  247. // To avoid work we use link_and_eval_module however that can already be
  248. // dangerous if the vm loaded other modules.
  249. auto& vm = this->vm();
  250. TRY(vm.link_and_eval_module(Badge<Bytecode::Interpreter> {}, module));
  251. vm.run_queued_promise_jobs();
  252. vm.run_queued_finalization_registry_cleanup_jobs();
  253. return js_undefined();
  254. }
  255. Interpreter::HandleExceptionResponse Interpreter::handle_exception(size_t& program_counter, Value exception)
  256. {
  257. reg(Register::exception()) = exception;
  258. m_scheduled_jump = {};
  259. auto handlers = current_executable().exception_handlers_for_offset(program_counter);
  260. if (!handlers.has_value()) {
  261. return HandleExceptionResponse::ExitFromExecutable;
  262. }
  263. auto& handler = handlers->handler_offset;
  264. auto& finalizer = handlers->finalizer_offset;
  265. VERIFY(!running_execution_context().unwind_contexts.is_empty());
  266. auto& unwind_context = running_execution_context().unwind_contexts.last();
  267. VERIFY(unwind_context.executable == m_current_executable);
  268. if (handler.has_value()) {
  269. program_counter = handler.value();
  270. return HandleExceptionResponse::ContinueInThisExecutable;
  271. }
  272. if (finalizer.has_value()) {
  273. program_counter = finalizer.value();
  274. return HandleExceptionResponse::ContinueInThisExecutable;
  275. }
  276. VERIFY_NOT_REACHED();
  277. }
  278. // FIXME: GCC takes a *long* time to compile with flattening, and it will time out our CI. :|
  279. #if defined(AK_COMPILER_CLANG)
  280. # define FLATTEN_ON_CLANG FLATTEN
  281. #else
  282. # define FLATTEN_ON_CLANG
  283. #endif
  284. FLATTEN_ON_CLANG void Interpreter::run_bytecode(size_t entry_point)
  285. {
  286. if (vm().did_reach_stack_space_limit()) {
  287. reg(Register::exception()) = vm().throw_completion<InternalError>(ErrorType::CallStackSizeExceeded).release_value().value();
  288. return;
  289. }
  290. auto& running_execution_context = this->running_execution_context();
  291. auto* arguments = running_execution_context.arguments.data();
  292. auto& accumulator = this->accumulator();
  293. auto& executable = current_executable();
  294. auto const* bytecode = executable.bytecode.data();
  295. size_t program_counter = entry_point;
  296. TemporaryChange change(m_program_counter, Optional<size_t&>(program_counter));
  297. // Declare a lookup table for computed goto with each of the `handle_*` labels
  298. // to avoid the overhead of a switch statement.
  299. // This is a GCC extension, but it's also supported by Clang.
  300. static void* const bytecode_dispatch_table[] = {
  301. #define SET_UP_LABEL(name) &&handle_##name,
  302. ENUMERATE_BYTECODE_OPS(SET_UP_LABEL)
  303. };
  304. #undef SET_UP_LABEL
  305. #define DISPATCH_NEXT(name) \
  306. do { \
  307. if constexpr (Op::name::IsVariableLength) \
  308. program_counter += instruction.length(); \
  309. else \
  310. program_counter += sizeof(Op::name); \
  311. auto& next_instruction = *reinterpret_cast<Instruction const*>(&bytecode[program_counter]); \
  312. goto* bytecode_dispatch_table[static_cast<size_t>(next_instruction.type())]; \
  313. } while (0)
  314. for (;;) {
  315. start:
  316. for (;;) {
  317. goto* bytecode_dispatch_table[static_cast<size_t>((*reinterpret_cast<Instruction const*>(&bytecode[program_counter])).type())];
  318. handle_GetArgument: {
  319. auto const& instruction = *reinterpret_cast<Op::GetArgument const*>(&bytecode[program_counter]);
  320. set(instruction.dst(), arguments[instruction.index()]);
  321. DISPATCH_NEXT(GetArgument);
  322. }
  323. handle_SetArgument: {
  324. auto const& instruction = *reinterpret_cast<Op::SetArgument const*>(&bytecode[program_counter]);
  325. arguments[instruction.index()] = get(instruction.src());
  326. DISPATCH_NEXT(SetArgument);
  327. }
  328. handle_Mov: {
  329. auto& instruction = *reinterpret_cast<Op::Mov const*>(&bytecode[program_counter]);
  330. set(instruction.dst(), get(instruction.src()));
  331. DISPATCH_NEXT(Mov);
  332. }
  333. handle_End: {
  334. auto& instruction = *reinterpret_cast<Op::End const*>(&bytecode[program_counter]);
  335. accumulator = get(instruction.value());
  336. return;
  337. }
  338. handle_Jump: {
  339. auto& instruction = *reinterpret_cast<Op::Jump const*>(&bytecode[program_counter]);
  340. program_counter = instruction.target().address();
  341. goto start;
  342. }
  343. handle_JumpIf: {
  344. auto& instruction = *reinterpret_cast<Op::JumpIf const*>(&bytecode[program_counter]);
  345. if (get(instruction.condition()).to_boolean())
  346. program_counter = instruction.true_target().address();
  347. else
  348. program_counter = instruction.false_target().address();
  349. goto start;
  350. }
  351. handle_JumpTrue: {
  352. auto& instruction = *reinterpret_cast<Op::JumpTrue const*>(&bytecode[program_counter]);
  353. if (get(instruction.condition()).to_boolean()) {
  354. program_counter = instruction.target().address();
  355. goto start;
  356. }
  357. DISPATCH_NEXT(JumpTrue);
  358. }
  359. handle_JumpFalse: {
  360. auto& instruction = *reinterpret_cast<Op::JumpFalse const*>(&bytecode[program_counter]);
  361. if (!get(instruction.condition()).to_boolean()) {
  362. program_counter = instruction.target().address();
  363. goto start;
  364. }
  365. DISPATCH_NEXT(JumpFalse);
  366. }
  367. handle_JumpNullish: {
  368. auto& instruction = *reinterpret_cast<Op::JumpNullish const*>(&bytecode[program_counter]);
  369. if (get(instruction.condition()).is_nullish())
  370. program_counter = instruction.true_target().address();
  371. else
  372. program_counter = instruction.false_target().address();
  373. goto start;
  374. }
  375. #define HANDLE_COMPARISON_OP(op_TitleCase, op_snake_case, numeric_operator) \
  376. handle_Jump##op_TitleCase: \
  377. { \
  378. auto& instruction = *reinterpret_cast<Op::Jump##op_TitleCase const*>(&bytecode[program_counter]); \
  379. auto lhs = get(instruction.lhs()); \
  380. auto rhs = get(instruction.rhs()); \
  381. if (lhs.is_number() && rhs.is_number()) { \
  382. bool result; \
  383. if (lhs.is_int32() && rhs.is_int32()) { \
  384. result = lhs.as_i32() numeric_operator rhs.as_i32(); \
  385. } else { \
  386. result = lhs.as_double() numeric_operator rhs.as_double(); \
  387. } \
  388. program_counter = result ? instruction.true_target().address() : instruction.false_target().address(); \
  389. goto start; \
  390. } \
  391. auto result = op_snake_case(vm(), get(instruction.lhs()), get(instruction.rhs())); \
  392. if (result.is_error()) { \
  393. if (handle_exception(program_counter, result.error_value()) == HandleExceptionResponse::ExitFromExecutable) \
  394. return; \
  395. goto start; \
  396. } \
  397. if (result.value().to_boolean()) \
  398. program_counter = instruction.true_target().address(); \
  399. else \
  400. program_counter = instruction.false_target().address(); \
  401. goto start; \
  402. }
  403. JS_ENUMERATE_COMPARISON_OPS(HANDLE_COMPARISON_OP)
  404. #undef HANDLE_COMPARISON_OP
  405. handle_JumpUndefined: {
  406. auto& instruction = *reinterpret_cast<Op::JumpUndefined const*>(&bytecode[program_counter]);
  407. if (get(instruction.condition()).is_undefined())
  408. program_counter = instruction.true_target().address();
  409. else
  410. program_counter = instruction.false_target().address();
  411. goto start;
  412. }
  413. handle_EnterUnwindContext: {
  414. auto& instruction = *reinterpret_cast<Op::EnterUnwindContext const*>(&bytecode[program_counter]);
  415. enter_unwind_context();
  416. program_counter = instruction.entry_point().address();
  417. goto start;
  418. }
  419. handle_ContinuePendingUnwind: {
  420. auto& instruction = *reinterpret_cast<Op::ContinuePendingUnwind const*>(&bytecode[program_counter]);
  421. if (auto exception = reg(Register::exception()); !exception.is_empty()) {
  422. if (handle_exception(program_counter, exception) == HandleExceptionResponse::ExitFromExecutable)
  423. return;
  424. goto start;
  425. }
  426. if (!saved_return_value().is_empty()) {
  427. do_return(saved_return_value());
  428. if (auto handlers = executable.exception_handlers_for_offset(program_counter); handlers.has_value()) {
  429. if (auto finalizer = handlers.value().finalizer_offset; finalizer.has_value()) {
  430. VERIFY(!running_execution_context.unwind_contexts.is_empty());
  431. auto& unwind_context = running_execution_context.unwind_contexts.last();
  432. VERIFY(unwind_context.executable == m_current_executable);
  433. reg(Register::saved_return_value()) = reg(Register::return_value());
  434. reg(Register::return_value()) = {};
  435. program_counter = finalizer.value();
  436. // the unwind_context will be pop'ed when entering the finally block
  437. goto start;
  438. }
  439. }
  440. return;
  441. }
  442. auto const old_scheduled_jump = running_execution_context.previously_scheduled_jumps.take_last();
  443. if (m_scheduled_jump.has_value()) {
  444. program_counter = m_scheduled_jump.value();
  445. m_scheduled_jump = {};
  446. } else {
  447. program_counter = instruction.resume_target().address();
  448. // set the scheduled jump to the old value if we continue
  449. // where we left it
  450. m_scheduled_jump = old_scheduled_jump;
  451. }
  452. goto start;
  453. }
  454. handle_ScheduleJump: {
  455. auto& instruction = *reinterpret_cast<Op::ScheduleJump const*>(&bytecode[program_counter]);
  456. m_scheduled_jump = instruction.target().address();
  457. auto finalizer = executable.exception_handlers_for_offset(program_counter).value().finalizer_offset;
  458. VERIFY(finalizer.has_value());
  459. program_counter = finalizer.value();
  460. goto start;
  461. }
  462. #define HANDLE_INSTRUCTION(name) \
  463. handle_##name: \
  464. { \
  465. auto& instruction = *reinterpret_cast<Op::name const*>(&bytecode[program_counter]); \
  466. { \
  467. auto result = instruction.execute_impl(*this); \
  468. if (result.is_error()) { \
  469. if (handle_exception(program_counter, result.error_value()) == HandleExceptionResponse::ExitFromExecutable) \
  470. return; \
  471. goto start; \
  472. } \
  473. } \
  474. DISPATCH_NEXT(name); \
  475. }
  476. #define HANDLE_INSTRUCTION_WITHOUT_EXCEPTION_CHECK(name) \
  477. handle_##name: \
  478. { \
  479. auto& instruction = *reinterpret_cast<Op::name const*>(&bytecode[program_counter]); \
  480. instruction.execute_impl(*this); \
  481. DISPATCH_NEXT(name); \
  482. }
  483. HANDLE_INSTRUCTION(Add);
  484. HANDLE_INSTRUCTION_WITHOUT_EXCEPTION_CHECK(AddPrivateName);
  485. HANDLE_INSTRUCTION(ArrayAppend);
  486. HANDLE_INSTRUCTION(AsyncIteratorClose);
  487. HANDLE_INSTRUCTION(BitwiseAnd);
  488. HANDLE_INSTRUCTION(BitwiseNot);
  489. HANDLE_INSTRUCTION(BitwiseOr);
  490. HANDLE_INSTRUCTION(BitwiseXor);
  491. HANDLE_INSTRUCTION_WITHOUT_EXCEPTION_CHECK(BlockDeclarationInstantiation);
  492. HANDLE_INSTRUCTION(Call);
  493. HANDLE_INSTRUCTION(CallWithArgumentArray);
  494. HANDLE_INSTRUCTION_WITHOUT_EXCEPTION_CHECK(Catch);
  495. HANDLE_INSTRUCTION(ConcatString);
  496. HANDLE_INSTRUCTION(CopyObjectExcludingProperties);
  497. HANDLE_INSTRUCTION_WITHOUT_EXCEPTION_CHECK(CreateLexicalEnvironment);
  498. HANDLE_INSTRUCTION_WITHOUT_EXCEPTION_CHECK(CreateVariableEnvironment);
  499. HANDLE_INSTRUCTION_WITHOUT_EXCEPTION_CHECK(CreatePrivateEnvironment);
  500. HANDLE_INSTRUCTION(CreateVariable);
  501. HANDLE_INSTRUCTION(CreateRestParams);
  502. HANDLE_INSTRUCTION(CreateArguments);
  503. HANDLE_INSTRUCTION(Decrement);
  504. HANDLE_INSTRUCTION(DeleteById);
  505. HANDLE_INSTRUCTION(DeleteByIdWithThis);
  506. HANDLE_INSTRUCTION(DeleteByValue);
  507. HANDLE_INSTRUCTION(DeleteByValueWithThis);
  508. HANDLE_INSTRUCTION(DeleteVariable);
  509. HANDLE_INSTRUCTION(Div);
  510. HANDLE_INSTRUCTION_WITHOUT_EXCEPTION_CHECK(Dump);
  511. HANDLE_INSTRUCTION(EnterObjectEnvironment);
  512. HANDLE_INSTRUCTION(Exp);
  513. HANDLE_INSTRUCTION(GetById);
  514. HANDLE_INSTRUCTION(GetByIdWithThis);
  515. HANDLE_INSTRUCTION(GetByValue);
  516. HANDLE_INSTRUCTION(GetByValueWithThis);
  517. HANDLE_INSTRUCTION(GetCalleeAndThisFromEnvironment);
  518. HANDLE_INSTRUCTION(GetGlobal);
  519. HANDLE_INSTRUCTION_WITHOUT_EXCEPTION_CHECK(GetImportMeta);
  520. HANDLE_INSTRUCTION(GetIterator);
  521. HANDLE_INSTRUCTION(GetLength);
  522. HANDLE_INSTRUCTION(GetLengthWithThis);
  523. HANDLE_INSTRUCTION(GetMethod);
  524. HANDLE_INSTRUCTION_WITHOUT_EXCEPTION_CHECK(GetNewTarget);
  525. HANDLE_INSTRUCTION(GetNextMethodFromIteratorRecord);
  526. HANDLE_INSTRUCTION(GetObjectFromIteratorRecord);
  527. HANDLE_INSTRUCTION(GetObjectPropertyIterator);
  528. HANDLE_INSTRUCTION(GetPrivateById);
  529. HANDLE_INSTRUCTION(GetBinding);
  530. HANDLE_INSTRUCTION(GreaterThan);
  531. HANDLE_INSTRUCTION(GreaterThanEquals);
  532. HANDLE_INSTRUCTION(HasPrivateId);
  533. HANDLE_INSTRUCTION(ImportCall);
  534. HANDLE_INSTRUCTION(In);
  535. HANDLE_INSTRUCTION(Increment);
  536. HANDLE_INSTRUCTION(InitializeLexicalBinding);
  537. HANDLE_INSTRUCTION(InitializeVariableBinding);
  538. HANDLE_INSTRUCTION(InstanceOf);
  539. HANDLE_INSTRUCTION(IteratorClose);
  540. HANDLE_INSTRUCTION(IteratorNext);
  541. HANDLE_INSTRUCTION(IteratorToArray);
  542. HANDLE_INSTRUCTION_WITHOUT_EXCEPTION_CHECK(LeaveFinally);
  543. HANDLE_INSTRUCTION_WITHOUT_EXCEPTION_CHECK(LeaveLexicalEnvironment);
  544. HANDLE_INSTRUCTION_WITHOUT_EXCEPTION_CHECK(LeavePrivateEnvironment);
  545. HANDLE_INSTRUCTION_WITHOUT_EXCEPTION_CHECK(LeaveUnwindContext);
  546. HANDLE_INSTRUCTION(LeftShift);
  547. HANDLE_INSTRUCTION(LessThan);
  548. HANDLE_INSTRUCTION(LessThanEquals);
  549. HANDLE_INSTRUCTION(LooselyEquals);
  550. HANDLE_INSTRUCTION(LooselyInequals);
  551. HANDLE_INSTRUCTION(Mod);
  552. HANDLE_INSTRUCTION(Mul);
  553. HANDLE_INSTRUCTION_WITHOUT_EXCEPTION_CHECK(NewArray);
  554. HANDLE_INSTRUCTION(NewClass);
  555. HANDLE_INSTRUCTION_WITHOUT_EXCEPTION_CHECK(NewFunction);
  556. HANDLE_INSTRUCTION_WITHOUT_EXCEPTION_CHECK(NewObject);
  557. HANDLE_INSTRUCTION_WITHOUT_EXCEPTION_CHECK(NewPrimitiveArray);
  558. HANDLE_INSTRUCTION_WITHOUT_EXCEPTION_CHECK(NewRegExp);
  559. HANDLE_INSTRUCTION_WITHOUT_EXCEPTION_CHECK(NewTypeError);
  560. HANDLE_INSTRUCTION(Not);
  561. HANDLE_INSTRUCTION_WITHOUT_EXCEPTION_CHECK(PrepareYield);
  562. HANDLE_INSTRUCTION(PostfixDecrement);
  563. HANDLE_INSTRUCTION(PostfixIncrement);
  564. HANDLE_INSTRUCTION(PutById);
  565. HANDLE_INSTRUCTION(PutByIdWithThis);
  566. HANDLE_INSTRUCTION(PutByValue);
  567. HANDLE_INSTRUCTION(PutByValueWithThis);
  568. HANDLE_INSTRUCTION(PutPrivateById);
  569. HANDLE_INSTRUCTION(ResolveSuperBase);
  570. HANDLE_INSTRUCTION(ResolveThisBinding);
  571. HANDLE_INSTRUCTION_WITHOUT_EXCEPTION_CHECK(RestoreScheduledJump);
  572. HANDLE_INSTRUCTION(RightShift);
  573. HANDLE_INSTRUCTION(SetLexicalBinding);
  574. HANDLE_INSTRUCTION(SetVariableBinding);
  575. HANDLE_INSTRUCTION(StrictlyEquals);
  576. HANDLE_INSTRUCTION(StrictlyInequals);
  577. HANDLE_INSTRUCTION(Sub);
  578. HANDLE_INSTRUCTION(SuperCallWithArgumentArray);
  579. HANDLE_INSTRUCTION(Throw);
  580. HANDLE_INSTRUCTION(ThrowIfNotObject);
  581. HANDLE_INSTRUCTION(ThrowIfNullish);
  582. HANDLE_INSTRUCTION(ThrowIfTDZ);
  583. HANDLE_INSTRUCTION(Typeof);
  584. HANDLE_INSTRUCTION(TypeofBinding);
  585. HANDLE_INSTRUCTION(UnaryMinus);
  586. HANDLE_INSTRUCTION(UnaryPlus);
  587. HANDLE_INSTRUCTION(UnsignedRightShift);
  588. handle_Await: {
  589. auto& instruction = *reinterpret_cast<Op::Await const*>(&bytecode[program_counter]);
  590. instruction.execute_impl(*this);
  591. return;
  592. }
  593. handle_Return: {
  594. auto& instruction = *reinterpret_cast<Op::Return const*>(&bytecode[program_counter]);
  595. instruction.execute_impl(*this);
  596. return;
  597. }
  598. handle_Yield: {
  599. auto& instruction = *reinterpret_cast<Op::Yield const*>(&bytecode[program_counter]);
  600. instruction.execute_impl(*this);
  601. // Note: A `yield` statement will not go through a finally statement,
  602. // hence we need to set a flag to not do so,
  603. // but we generate a Yield Operation in the case of returns in
  604. // generators as well, so we need to check if it will actually
  605. // continue or is a `return` in disguise
  606. return;
  607. }
  608. }
  609. }
  610. }
  611. Interpreter::ResultAndReturnRegister Interpreter::run_executable(Executable& executable, Optional<size_t> entry_point, Value initial_accumulator_value)
  612. {
  613. dbgln_if(JS_BYTECODE_DEBUG, "Bytecode::Interpreter will run unit {:p}", &executable);
  614. TemporaryChange restore_executable { m_current_executable, GCPtr { executable } };
  615. TemporaryChange restore_saved_jump { m_scheduled_jump, Optional<size_t> {} };
  616. TemporaryChange restore_realm { m_realm, GCPtr { vm().current_realm() } };
  617. TemporaryChange restore_global_object { m_global_object, GCPtr { m_realm->global_object() } };
  618. TemporaryChange restore_global_declarative_environment { m_global_declarative_environment, GCPtr { m_realm->global_environment().declarative_record() } };
  619. VERIFY(!vm().execution_context_stack().is_empty());
  620. auto& running_execution_context = vm().running_execution_context();
  621. u32 registers_and_constants_and_locals_count = executable.number_of_registers + executable.constants.size() + executable.local_variable_names.size();
  622. if (running_execution_context.registers_and_constants_and_locals.size() < registers_and_constants_and_locals_count)
  623. running_execution_context.registers_and_constants_and_locals.resize(registers_and_constants_and_locals_count);
  624. TemporaryChange restore_running_execution_context { m_running_execution_context, &running_execution_context };
  625. TemporaryChange restore_arguments { m_arguments, running_execution_context.arguments.span() };
  626. TemporaryChange restore_registers_and_constants_and_locals { m_registers_and_constants_and_locals, running_execution_context.registers_and_constants_and_locals.span() };
  627. reg(Register::accumulator()) = initial_accumulator_value;
  628. reg(Register::return_value()) = {};
  629. // NOTE: We only copy the `this` value from ExecutionContext if it's not already set.
  630. // If we are re-entering an async/generator context, the `this` value
  631. // may have already been cached by a ResolveThisBinding instruction,
  632. // and subsequent instructions expect this value to be set.
  633. if (reg(Register::this_value()).is_empty())
  634. reg(Register::this_value()) = running_execution_context.this_value;
  635. running_execution_context.executable = &executable;
  636. for (size_t i = 0; i < executable.constants.size(); ++i) {
  637. running_execution_context.registers_and_constants_and_locals[executable.number_of_registers + i] = executable.constants[i];
  638. }
  639. run_bytecode(entry_point.value_or(0));
  640. dbgln_if(JS_BYTECODE_DEBUG, "Bytecode::Interpreter did run unit {:p}", &executable);
  641. if constexpr (JS_BYTECODE_DEBUG) {
  642. auto const& registers_and_constants_and_locals = running_execution_context.registers_and_constants_and_locals;
  643. for (size_t i = 0; i < executable.number_of_registers; ++i) {
  644. String value_string;
  645. if (registers_and_constants_and_locals[i].is_empty())
  646. value_string = "(empty)"_string;
  647. else
  648. value_string = registers_and_constants_and_locals[i].to_string_without_side_effects();
  649. dbgln("[{:3}] {}", i, value_string);
  650. }
  651. }
  652. auto return_value = js_undefined();
  653. if (!reg(Register::return_value()).is_empty())
  654. return_value = reg(Register::return_value());
  655. else if (!reg(Register::saved_return_value()).is_empty())
  656. return_value = reg(Register::saved_return_value());
  657. auto exception = reg(Register::exception());
  658. // At this point we may have already run any queued promise jobs via on_call_stack_emptied,
  659. // in which case this is a no-op.
  660. vm().run_queued_promise_jobs();
  661. vm().finish_execution_generation();
  662. if (!exception.is_empty())
  663. return { throw_completion(exception), running_execution_context.registers_and_constants_and_locals[0] };
  664. return { return_value, running_execution_context.registers_and_constants_and_locals[0] };
  665. }
  666. void Interpreter::enter_unwind_context()
  667. {
  668. running_execution_context().unwind_contexts.empend(
  669. m_current_executable,
  670. running_execution_context().lexical_environment);
  671. running_execution_context().previously_scheduled_jumps.append(m_scheduled_jump);
  672. m_scheduled_jump = {};
  673. }
  674. void Interpreter::leave_unwind_context()
  675. {
  676. running_execution_context().unwind_contexts.take_last();
  677. }
  678. void Interpreter::catch_exception(Operand dst)
  679. {
  680. set(dst, reg(Register::exception()));
  681. reg(Register::exception()) = {};
  682. auto& context = running_execution_context().unwind_contexts.last();
  683. VERIFY(!context.handler_called);
  684. VERIFY(context.executable == &current_executable());
  685. context.handler_called = true;
  686. running_execution_context().lexical_environment = context.lexical_environment;
  687. }
  688. void Interpreter::restore_scheduled_jump()
  689. {
  690. m_scheduled_jump = running_execution_context().previously_scheduled_jumps.take_last();
  691. }
  692. void Interpreter::leave_finally()
  693. {
  694. reg(Register::exception()) = {};
  695. m_scheduled_jump = running_execution_context().previously_scheduled_jumps.take_last();
  696. }
  697. void Interpreter::enter_object_environment(Object& object)
  698. {
  699. auto& old_environment = running_execution_context().lexical_environment;
  700. running_execution_context().saved_lexical_environments.append(old_environment);
  701. running_execution_context().lexical_environment = new_object_environment(object, true, old_environment);
  702. }
  703. ThrowCompletionOr<NonnullGCPtr<Bytecode::Executable>> compile(VM& vm, ASTNode const& node, FunctionKind kind, DeprecatedFlyString const& name)
  704. {
  705. auto executable_result = Bytecode::Generator::generate_from_ast_node(vm, node, kind);
  706. if (executable_result.is_error())
  707. return vm.throw_completion<InternalError>(ErrorType::NotImplemented, TRY_OR_THROW_OOM(vm, executable_result.error().to_string()));
  708. auto bytecode_executable = executable_result.release_value();
  709. bytecode_executable->name = name;
  710. if (Bytecode::g_dump_bytecode)
  711. bytecode_executable->dump();
  712. return bytecode_executable;
  713. }
  714. ThrowCompletionOr<NonnullGCPtr<Bytecode::Executable>> compile(VM& vm, ECMAScriptFunctionObject const& function)
  715. {
  716. auto const& name = function.name();
  717. auto executable_result = Bytecode::Generator::generate_from_function(vm, function);
  718. if (executable_result.is_error())
  719. return vm.throw_completion<InternalError>(ErrorType::NotImplemented, TRY_OR_THROW_OOM(vm, executable_result.error().to_string()));
  720. auto bytecode_executable = executable_result.release_value();
  721. bytecode_executable->name = name;
  722. if (Bytecode::g_dump_bytecode)
  723. bytecode_executable->dump();
  724. return bytecode_executable;
  725. }
  726. // NOTE: This function assumes that the index is valid within the TypedArray,
  727. // and that the TypedArray is not detached.
  728. template<typename T>
  729. inline Value fast_typed_array_get_element(TypedArrayBase& typed_array, u32 index)
  730. {
  731. Checked<u32> offset_into_array_buffer = index;
  732. offset_into_array_buffer *= sizeof(T);
  733. offset_into_array_buffer += typed_array.byte_offset();
  734. if (offset_into_array_buffer.has_overflow()) [[unlikely]] {
  735. return js_undefined();
  736. }
  737. auto const& array_buffer = *typed_array.viewed_array_buffer();
  738. auto const* slot = reinterpret_cast<T const*>(array_buffer.buffer().offset_pointer(offset_into_array_buffer.value()));
  739. return Value { *slot };
  740. }
  741. // NOTE: This function assumes that the index is valid within the TypedArray,
  742. // and that the TypedArray is not detached.
  743. template<typename T>
  744. inline void fast_typed_array_set_element(TypedArrayBase& typed_array, u32 index, T value)
  745. {
  746. Checked<u32> offset_into_array_buffer = index;
  747. offset_into_array_buffer *= sizeof(T);
  748. offset_into_array_buffer += typed_array.byte_offset();
  749. if (offset_into_array_buffer.has_overflow()) [[unlikely]] {
  750. return;
  751. }
  752. auto& array_buffer = *typed_array.viewed_array_buffer();
  753. auto* slot = reinterpret_cast<T*>(array_buffer.buffer().offset_pointer(offset_into_array_buffer.value()));
  754. *slot = value;
  755. }
  756. static Completion throw_null_or_undefined_property_get(VM& vm, Value base_value, Optional<IdentifierTableIndex> base_identifier, IdentifierTableIndex property_identifier, Executable const& executable)
  757. {
  758. VERIFY(base_value.is_nullish());
  759. if (base_identifier.has_value())
  760. return vm.throw_completion<TypeError>(ErrorType::ToObjectNullOrUndefinedWithPropertyAndName, executable.get_identifier(property_identifier), base_value, executable.get_identifier(base_identifier.value()));
  761. return vm.throw_completion<TypeError>(ErrorType::ToObjectNullOrUndefinedWithProperty, executable.get_identifier(property_identifier), base_value);
  762. }
  763. static Completion throw_null_or_undefined_property_get(VM& vm, Value base_value, Optional<IdentifierTableIndex> base_identifier, Value property, Executable const& executable)
  764. {
  765. VERIFY(base_value.is_nullish());
  766. if (base_identifier.has_value())
  767. return vm.throw_completion<TypeError>(ErrorType::ToObjectNullOrUndefinedWithPropertyAndName, property, base_value, executable.get_identifier(base_identifier.value()));
  768. return vm.throw_completion<TypeError>(ErrorType::ToObjectNullOrUndefinedWithProperty, property, base_value);
  769. }
  770. template<typename BaseType, typename PropertyType>
  771. ALWAYS_INLINE Completion throw_null_or_undefined_property_access(VM& vm, Value base_value, BaseType const& base_identifier, PropertyType const& property_identifier)
  772. {
  773. VERIFY(base_value.is_nullish());
  774. bool has_base_identifier = true;
  775. bool has_property_identifier = true;
  776. if constexpr (requires { base_identifier.has_value(); })
  777. has_base_identifier = base_identifier.has_value();
  778. if constexpr (requires { property_identifier.has_value(); })
  779. has_property_identifier = property_identifier.has_value();
  780. if (has_base_identifier && has_property_identifier)
  781. return vm.throw_completion<TypeError>(ErrorType::ToObjectNullOrUndefinedWithPropertyAndName, property_identifier, base_value, base_identifier);
  782. if (has_property_identifier)
  783. return vm.throw_completion<TypeError>(ErrorType::ToObjectNullOrUndefinedWithProperty, property_identifier, base_value);
  784. if (has_base_identifier)
  785. return vm.throw_completion<TypeError>(ErrorType::ToObjectNullOrUndefinedWithName, base_identifier, base_value);
  786. return vm.throw_completion<TypeError>(ErrorType::ToObjectNullOrUndefined);
  787. }
  788. ALWAYS_INLINE GCPtr<Object> base_object_for_get_impl(VM& vm, Value base_value)
  789. {
  790. if (base_value.is_object()) [[likely]]
  791. return base_value.as_object();
  792. // OPTIMIZATION: For various primitives we can avoid actually creating a new object for them.
  793. auto& realm = *vm.current_realm();
  794. if (base_value.is_string())
  795. return realm.intrinsics().string_prototype();
  796. if (base_value.is_number())
  797. return realm.intrinsics().number_prototype();
  798. if (base_value.is_boolean())
  799. return realm.intrinsics().boolean_prototype();
  800. if (base_value.is_bigint())
  801. return realm.intrinsics().bigint_prototype();
  802. if (base_value.is_symbol())
  803. return realm.intrinsics().symbol_prototype();
  804. return nullptr;
  805. }
  806. ALWAYS_INLINE ThrowCompletionOr<NonnullGCPtr<Object>> base_object_for_get(VM& vm, Value base_value, Optional<IdentifierTableIndex> base_identifier, IdentifierTableIndex property_identifier, Executable const& executable)
  807. {
  808. if (auto base_object = base_object_for_get_impl(vm, base_value))
  809. return NonnullGCPtr { *base_object };
  810. // NOTE: At this point this is guaranteed to throw (null or undefined).
  811. return throw_null_or_undefined_property_get(vm, base_value, base_identifier, property_identifier, executable);
  812. }
  813. ALWAYS_INLINE ThrowCompletionOr<NonnullGCPtr<Object>> base_object_for_get(VM& vm, Value base_value, Optional<IdentifierTableIndex> base_identifier, Value property, Executable const& executable)
  814. {
  815. if (auto base_object = base_object_for_get_impl(vm, base_value))
  816. return NonnullGCPtr { *base_object };
  817. // NOTE: At this point this is guaranteed to throw (null or undefined).
  818. return throw_null_or_undefined_property_get(vm, base_value, base_identifier, property, executable);
  819. }
  820. enum class GetByIdMode {
  821. Normal,
  822. Length,
  823. };
  824. template<GetByIdMode mode = GetByIdMode::Normal>
  825. inline ThrowCompletionOr<Value> get_by_id(VM& vm, Optional<IdentifierTableIndex> base_identifier, IdentifierTableIndex property, Value base_value, Value this_value, PropertyLookupCache& cache, Executable const& executable)
  826. {
  827. if constexpr (mode == GetByIdMode::Length) {
  828. if (base_value.is_string()) {
  829. return Value(base_value.as_string().utf16_string().length_in_code_units());
  830. }
  831. }
  832. auto base_obj = TRY(base_object_for_get(vm, base_value, base_identifier, property, executable));
  833. if constexpr (mode == GetByIdMode::Length) {
  834. // OPTIMIZATION: Fast path for the magical "length" property on Array objects.
  835. if (base_obj->has_magical_length_property()) {
  836. return Value { base_obj->indexed_properties().array_like_size() };
  837. }
  838. }
  839. auto& shape = base_obj->shape();
  840. if (cache.prototype) {
  841. // OPTIMIZATION: If the prototype chain hasn't been mutated in a way that would invalidate the cache, we can use it.
  842. bool can_use_cache = [&]() -> bool {
  843. if (&shape != cache.shape)
  844. return false;
  845. if (!cache.prototype_chain_validity)
  846. return false;
  847. if (!cache.prototype_chain_validity->is_valid())
  848. return false;
  849. return true;
  850. }();
  851. if (can_use_cache) {
  852. auto value = cache.prototype->get_direct(cache.property_offset.value());
  853. if (value.is_accessor())
  854. return TRY(call(vm, value.as_accessor().getter(), this_value));
  855. return value;
  856. }
  857. } else if (&shape == cache.shape) {
  858. // OPTIMIZATION: If the shape of the object hasn't changed, we can use the cached property offset.
  859. auto value = base_obj->get_direct(cache.property_offset.value());
  860. if (value.is_accessor())
  861. return TRY(call(vm, value.as_accessor().getter(), this_value));
  862. return value;
  863. }
  864. CacheablePropertyMetadata cacheable_metadata;
  865. auto value = TRY(base_obj->internal_get(executable.get_identifier(property), this_value, &cacheable_metadata));
  866. if (cacheable_metadata.type == CacheablePropertyMetadata::Type::OwnProperty) {
  867. cache = {};
  868. cache.shape = shape;
  869. cache.property_offset = cacheable_metadata.property_offset.value();
  870. } else if (cacheable_metadata.type == CacheablePropertyMetadata::Type::InPrototypeChain) {
  871. cache = {};
  872. cache.shape = &base_obj->shape();
  873. cache.property_offset = cacheable_metadata.property_offset.value();
  874. cache.prototype = *cacheable_metadata.prototype;
  875. cache.prototype_chain_validity = *cacheable_metadata.prototype->shape().prototype_chain_validity();
  876. }
  877. return value;
  878. }
  879. inline ThrowCompletionOr<Value> get_by_value(VM& vm, Optional<IdentifierTableIndex> base_identifier, Value base_value, Value property_key_value, Executable const& executable)
  880. {
  881. // OPTIMIZATION: Fast path for simple Int32 indexes in array-like objects.
  882. if (base_value.is_object() && property_key_value.is_int32() && property_key_value.as_i32() >= 0) {
  883. auto& object = base_value.as_object();
  884. auto index = static_cast<u32>(property_key_value.as_i32());
  885. auto const* object_storage = object.indexed_properties().storage();
  886. // For "non-typed arrays":
  887. if (!object.may_interfere_with_indexed_property_access()
  888. && object_storage) {
  889. auto maybe_value = [&] {
  890. if (object_storage->is_simple_storage())
  891. return static_cast<SimpleIndexedPropertyStorage const*>(object_storage)->inline_get(index);
  892. else
  893. return static_cast<GenericIndexedPropertyStorage const*>(object_storage)->get(index);
  894. }();
  895. if (maybe_value.has_value()) {
  896. auto value = maybe_value->value;
  897. if (!value.is_accessor())
  898. return value;
  899. }
  900. }
  901. // For typed arrays:
  902. if (object.is_typed_array()) {
  903. auto& typed_array = static_cast<TypedArrayBase&>(object);
  904. auto canonical_index = CanonicalIndex { CanonicalIndex::Type::Index, index };
  905. if (is_valid_integer_index(typed_array, canonical_index)) {
  906. switch (typed_array.kind()) {
  907. case TypedArrayBase::Kind::Uint8Array:
  908. return fast_typed_array_get_element<u8>(typed_array, index);
  909. case TypedArrayBase::Kind::Uint16Array:
  910. return fast_typed_array_get_element<u16>(typed_array, index);
  911. case TypedArrayBase::Kind::Uint32Array:
  912. return fast_typed_array_get_element<u32>(typed_array, index);
  913. case TypedArrayBase::Kind::Int8Array:
  914. return fast_typed_array_get_element<i8>(typed_array, index);
  915. case TypedArrayBase::Kind::Int16Array:
  916. return fast_typed_array_get_element<i16>(typed_array, index);
  917. case TypedArrayBase::Kind::Int32Array:
  918. return fast_typed_array_get_element<i32>(typed_array, index);
  919. case TypedArrayBase::Kind::Uint8ClampedArray:
  920. return fast_typed_array_get_element<u8>(typed_array, index);
  921. default:
  922. // FIXME: Support more TypedArray kinds.
  923. break;
  924. }
  925. }
  926. switch (typed_array.kind()) {
  927. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, Type) \
  928. case TypedArrayBase::Kind::ClassName: \
  929. return typed_array_get_element<Type>(typed_array, canonical_index);
  930. JS_ENUMERATE_TYPED_ARRAYS
  931. #undef __JS_ENUMERATE
  932. }
  933. }
  934. }
  935. auto object = TRY(base_object_for_get(vm, base_value, base_identifier, property_key_value, executable));
  936. auto property_key = TRY(property_key_value.to_property_key(vm));
  937. if (base_value.is_string()) {
  938. auto string_value = TRY(base_value.as_string().get(vm, property_key));
  939. if (string_value.has_value())
  940. return *string_value;
  941. }
  942. return TRY(object->internal_get(property_key, base_value));
  943. }
  944. inline ThrowCompletionOr<Value> get_global(Interpreter& interpreter, IdentifierTableIndex identifier_index, GlobalVariableCache& cache)
  945. {
  946. auto& vm = interpreter.vm();
  947. auto& binding_object = interpreter.global_object();
  948. auto& declarative_record = interpreter.global_declarative_environment();
  949. auto& shape = binding_object.shape();
  950. if (cache.environment_serial_number == declarative_record.environment_serial_number()) {
  951. // OPTIMIZATION: For global var bindings, if the shape of the global object hasn't changed,
  952. // we can use the cached property offset.
  953. if (&shape == cache.shape) {
  954. auto value = binding_object.get_direct(cache.property_offset.value());
  955. if (value.is_accessor())
  956. return TRY(call(vm, value.as_accessor().getter(), js_undefined()));
  957. }
  958. // OPTIMIZATION: For global lexical bindings, if the global declarative environment hasn't changed,
  959. // we can use the cached environment binding index.
  960. if (cache.environment_binding_index.has_value())
  961. return declarative_record.get_binding_value_direct(vm, cache.environment_binding_index.value());
  962. }
  963. cache.environment_serial_number = declarative_record.environment_serial_number();
  964. auto& identifier = interpreter.current_executable().get_identifier(identifier_index);
  965. if (vm.running_execution_context().script_or_module.has<NonnullGCPtr<Module>>()) {
  966. // NOTE: GetGlobal is used to access variables stored in the module environment and global environment.
  967. // The module environment is checked first since it precedes the global environment in the environment chain.
  968. auto& module_environment = *vm.running_execution_context().script_or_module.get<NonnullGCPtr<Module>>()->environment();
  969. if (TRY(module_environment.has_binding(identifier))) {
  970. // TODO: Cache offset of binding value
  971. return TRY(module_environment.get_binding_value(vm, identifier, vm.in_strict_mode()));
  972. }
  973. }
  974. Optional<size_t> offset;
  975. if (TRY(declarative_record.has_binding(identifier, &offset))) {
  976. cache.environment_binding_index = static_cast<u32>(offset.value());
  977. return TRY(declarative_record.get_binding_value(vm, identifier, vm.in_strict_mode()));
  978. }
  979. if (TRY(binding_object.has_property(identifier))) {
  980. CacheablePropertyMetadata cacheable_metadata;
  981. auto value = TRY(binding_object.internal_get(identifier, js_undefined(), &cacheable_metadata));
  982. if (cacheable_metadata.type == CacheablePropertyMetadata::Type::OwnProperty) {
  983. cache.shape = shape;
  984. cache.property_offset = cacheable_metadata.property_offset.value();
  985. }
  986. return value;
  987. }
  988. return vm.throw_completion<ReferenceError>(ErrorType::UnknownIdentifier, identifier);
  989. }
  990. inline ThrowCompletionOr<void> put_by_property_key(VM& vm, Value base, Value this_value, Value value, Optional<DeprecatedFlyString const&> const& base_identifier, PropertyKey name, Op::PropertyKind kind, PropertyLookupCache* cache = nullptr)
  991. {
  992. // Better error message than to_object would give
  993. if (vm.in_strict_mode() && base.is_nullish())
  994. return vm.throw_completion<TypeError>(ErrorType::ReferenceNullishSetProperty, name, base.to_string_without_side_effects());
  995. // a. Let baseObj be ? ToObject(V.[[Base]]).
  996. auto maybe_object = base.to_object(vm);
  997. if (maybe_object.is_error())
  998. return throw_null_or_undefined_property_access(vm, base, base_identifier, name);
  999. auto object = maybe_object.release_value();
  1000. if (kind == Op::PropertyKind::Getter || kind == Op::PropertyKind::Setter) {
  1001. // The generator should only pass us functions for getters and setters.
  1002. VERIFY(value.is_function());
  1003. }
  1004. switch (kind) {
  1005. case Op::PropertyKind::Getter: {
  1006. auto& function = value.as_function();
  1007. if (function.name().is_empty() && is<ECMAScriptFunctionObject>(function))
  1008. static_cast<ECMAScriptFunctionObject*>(&function)->set_name(ByteString::formatted("get {}", name));
  1009. object->define_direct_accessor(name, &function, nullptr, Attribute::Configurable | Attribute::Enumerable);
  1010. break;
  1011. }
  1012. case Op::PropertyKind::Setter: {
  1013. auto& function = value.as_function();
  1014. if (function.name().is_empty() && is<ECMAScriptFunctionObject>(function))
  1015. static_cast<ECMAScriptFunctionObject*>(&function)->set_name(ByteString::formatted("set {}", name));
  1016. object->define_direct_accessor(name, nullptr, &function, Attribute::Configurable | Attribute::Enumerable);
  1017. break;
  1018. }
  1019. case Op::PropertyKind::KeyValue: {
  1020. if (cache && cache->shape == &object->shape()) {
  1021. object->put_direct(*cache->property_offset, value);
  1022. return {};
  1023. }
  1024. CacheablePropertyMetadata cacheable_metadata;
  1025. bool succeeded = TRY(object->internal_set(name, value, this_value, &cacheable_metadata));
  1026. if (succeeded && cache && cacheable_metadata.type == CacheablePropertyMetadata::Type::OwnProperty) {
  1027. cache->shape = object->shape();
  1028. cache->property_offset = cacheable_metadata.property_offset.value();
  1029. }
  1030. if (!succeeded && vm.in_strict_mode()) {
  1031. if (base.is_object())
  1032. return vm.throw_completion<TypeError>(ErrorType::ReferenceNullishSetProperty, name, base.to_string_without_side_effects());
  1033. return vm.throw_completion<TypeError>(ErrorType::ReferencePrimitiveSetProperty, name, base.typeof_(vm)->utf8_string(), base.to_string_without_side_effects());
  1034. }
  1035. break;
  1036. }
  1037. case Op::PropertyKind::DirectKeyValue:
  1038. object->define_direct_property(name, value, Attribute::Enumerable | Attribute::Writable | Attribute::Configurable);
  1039. break;
  1040. case Op::PropertyKind::Spread:
  1041. TRY(object->copy_data_properties(vm, value, {}));
  1042. break;
  1043. case Op::PropertyKind::ProtoSetter:
  1044. if (value.is_object() || value.is_null())
  1045. MUST(object->internal_set_prototype_of(value.is_object() ? &value.as_object() : nullptr));
  1046. break;
  1047. }
  1048. return {};
  1049. }
  1050. inline ThrowCompletionOr<Value> perform_call(Interpreter& interpreter, Value this_value, Op::CallType call_type, Value callee, ReadonlySpan<Value> argument_values)
  1051. {
  1052. auto& vm = interpreter.vm();
  1053. auto& function = callee.as_function();
  1054. Value return_value;
  1055. if (call_type == Op::CallType::DirectEval) {
  1056. if (callee == interpreter.realm().intrinsics().eval_function())
  1057. return_value = TRY(perform_eval(vm, !argument_values.is_empty() ? argument_values[0].value_or(JS::js_undefined()) : js_undefined(), vm.in_strict_mode() ? CallerMode::Strict : CallerMode::NonStrict, EvalMode::Direct));
  1058. else
  1059. return_value = TRY(JS::call(vm, function, this_value, argument_values));
  1060. } else if (call_type == Op::CallType::Call)
  1061. return_value = TRY(JS::call(vm, function, this_value, argument_values));
  1062. else
  1063. return_value = TRY(construct(vm, function, argument_values));
  1064. return return_value;
  1065. }
  1066. static inline Completion throw_type_error_for_callee(Bytecode::Interpreter& interpreter, Value callee, StringView callee_type, Optional<StringTableIndex> const& expression_string)
  1067. {
  1068. auto& vm = interpreter.vm();
  1069. if (expression_string.has_value())
  1070. return vm.throw_completion<TypeError>(ErrorType::IsNotAEvaluatedFrom, callee.to_string_without_side_effects(), callee_type, interpreter.current_executable().get_string(expression_string->value()));
  1071. return vm.throw_completion<TypeError>(ErrorType::IsNotA, callee.to_string_without_side_effects(), callee_type);
  1072. }
  1073. inline ThrowCompletionOr<void> throw_if_needed_for_call(Interpreter& interpreter, Value callee, Op::CallType call_type, Optional<StringTableIndex> const& expression_string)
  1074. {
  1075. if ((call_type == Op::CallType::Call || call_type == Op::CallType::DirectEval)
  1076. && !callee.is_function())
  1077. return throw_type_error_for_callee(interpreter, callee, "function"sv, expression_string);
  1078. if (call_type == Op::CallType::Construct && !callee.is_constructor())
  1079. return throw_type_error_for_callee(interpreter, callee, "constructor"sv, expression_string);
  1080. return {};
  1081. }
  1082. inline Value new_function(VM& vm, FunctionNode const& function_node, Optional<IdentifierTableIndex> const& lhs_name, Optional<Operand> const& home_object)
  1083. {
  1084. Value value;
  1085. if (!function_node.has_name()) {
  1086. DeprecatedFlyString name = {};
  1087. if (lhs_name.has_value())
  1088. name = vm.bytecode_interpreter().current_executable().get_identifier(lhs_name.value());
  1089. value = function_node.instantiate_ordinary_function_expression(vm, name);
  1090. } else {
  1091. value = ECMAScriptFunctionObject::create(*vm.current_realm(), function_node.name(), function_node.source_text(), function_node.body(), function_node.parameters(), function_node.function_length(), function_node.local_variables_names(), vm.lexical_environment(), vm.running_execution_context().private_environment, function_node.kind(), function_node.is_strict_mode(),
  1092. function_node.parsing_insights(), function_node.is_arrow_function());
  1093. }
  1094. if (home_object.has_value()) {
  1095. auto home_object_value = vm.bytecode_interpreter().get(home_object.value());
  1096. static_cast<ECMAScriptFunctionObject&>(value.as_function()).set_home_object(&home_object_value.as_object());
  1097. }
  1098. return value;
  1099. }
  1100. inline ThrowCompletionOr<void> put_by_value(VM& vm, Value base, Optional<DeprecatedFlyString const&> const& base_identifier, Value property_key_value, Value value, Op::PropertyKind kind)
  1101. {
  1102. // OPTIMIZATION: Fast path for simple Int32 indexes in array-like objects.
  1103. if ((kind == Op::PropertyKind::KeyValue || kind == Op::PropertyKind::DirectKeyValue)
  1104. && base.is_object() && property_key_value.is_int32() && property_key_value.as_i32() >= 0) {
  1105. auto& object = base.as_object();
  1106. auto* storage = object.indexed_properties().storage();
  1107. auto index = static_cast<u32>(property_key_value.as_i32());
  1108. // For "non-typed arrays":
  1109. if (storage
  1110. && storage->is_simple_storage()
  1111. && !object.may_interfere_with_indexed_property_access()) {
  1112. auto maybe_value = storage->get(index);
  1113. if (maybe_value.has_value()) {
  1114. auto existing_value = maybe_value->value;
  1115. if (!existing_value.is_accessor()) {
  1116. storage->put(index, value);
  1117. return {};
  1118. }
  1119. }
  1120. }
  1121. // For typed arrays:
  1122. if (object.is_typed_array()) {
  1123. auto& typed_array = static_cast<TypedArrayBase&>(object);
  1124. auto canonical_index = CanonicalIndex { CanonicalIndex::Type::Index, index };
  1125. if (value.is_int32() && is_valid_integer_index(typed_array, canonical_index)) {
  1126. switch (typed_array.kind()) {
  1127. case TypedArrayBase::Kind::Uint8Array:
  1128. fast_typed_array_set_element<u8>(typed_array, index, static_cast<u8>(value.as_i32()));
  1129. return {};
  1130. case TypedArrayBase::Kind::Uint16Array:
  1131. fast_typed_array_set_element<u16>(typed_array, index, static_cast<u16>(value.as_i32()));
  1132. return {};
  1133. case TypedArrayBase::Kind::Uint32Array:
  1134. fast_typed_array_set_element<u32>(typed_array, index, static_cast<u32>(value.as_i32()));
  1135. return {};
  1136. case TypedArrayBase::Kind::Int8Array:
  1137. fast_typed_array_set_element<i8>(typed_array, index, static_cast<i8>(value.as_i32()));
  1138. return {};
  1139. case TypedArrayBase::Kind::Int16Array:
  1140. fast_typed_array_set_element<i16>(typed_array, index, static_cast<i16>(value.as_i32()));
  1141. return {};
  1142. case TypedArrayBase::Kind::Int32Array:
  1143. fast_typed_array_set_element<i32>(typed_array, index, value.as_i32());
  1144. return {};
  1145. case TypedArrayBase::Kind::Uint8ClampedArray:
  1146. fast_typed_array_set_element<u8>(typed_array, index, clamp(value.as_i32(), 0, 255));
  1147. return {};
  1148. default:
  1149. // FIXME: Support more TypedArray kinds.
  1150. break;
  1151. }
  1152. }
  1153. if (typed_array.kind() == TypedArrayBase::Kind::Uint32Array && value.is_integral_number()) {
  1154. auto integer = value.as_double();
  1155. if (AK::is_within_range<u32>(integer) && is_valid_integer_index(typed_array, canonical_index)) {
  1156. fast_typed_array_set_element<u32>(typed_array, index, static_cast<u32>(integer));
  1157. return {};
  1158. }
  1159. }
  1160. switch (typed_array.kind()) {
  1161. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, Type) \
  1162. case TypedArrayBase::Kind::ClassName: \
  1163. return typed_array_set_element<Type>(typed_array, canonical_index, value);
  1164. JS_ENUMERATE_TYPED_ARRAYS
  1165. #undef __JS_ENUMERATE
  1166. }
  1167. return {};
  1168. }
  1169. }
  1170. auto property_key = kind != Op::PropertyKind::Spread ? TRY(property_key_value.to_property_key(vm)) : PropertyKey {};
  1171. TRY(put_by_property_key(vm, base, base, value, base_identifier, property_key, kind));
  1172. return {};
  1173. }
  1174. struct CalleeAndThis {
  1175. Value callee;
  1176. Value this_value;
  1177. };
  1178. inline ThrowCompletionOr<CalleeAndThis> get_callee_and_this_from_environment(Bytecode::Interpreter& interpreter, DeprecatedFlyString const& name, EnvironmentCoordinate& cache)
  1179. {
  1180. auto& vm = interpreter.vm();
  1181. Value callee = js_undefined();
  1182. Value this_value = js_undefined();
  1183. if (cache.is_valid()) {
  1184. auto const* environment = interpreter.running_execution_context().lexical_environment.ptr();
  1185. for (size_t i = 0; i < cache.hops; ++i)
  1186. environment = environment->outer_environment();
  1187. if (!environment->is_permanently_screwed_by_eval()) {
  1188. callee = TRY(static_cast<DeclarativeEnvironment const&>(*environment).get_binding_value_direct(vm, cache.index));
  1189. this_value = js_undefined();
  1190. if (auto base_object = environment->with_base_object())
  1191. this_value = base_object;
  1192. return CalleeAndThis {
  1193. .callee = callee,
  1194. .this_value = this_value,
  1195. };
  1196. }
  1197. cache = {};
  1198. }
  1199. auto reference = TRY(vm.resolve_binding(name));
  1200. if (reference.environment_coordinate().has_value())
  1201. cache = reference.environment_coordinate().value();
  1202. callee = TRY(reference.get_value(vm));
  1203. if (reference.is_property_reference()) {
  1204. this_value = reference.get_this_value();
  1205. } else {
  1206. if (reference.is_environment_reference()) {
  1207. if (auto base_object = reference.base_environment().with_base_object(); base_object != nullptr)
  1208. this_value = base_object;
  1209. }
  1210. }
  1211. return CalleeAndThis {
  1212. .callee = callee,
  1213. .this_value = this_value,
  1214. };
  1215. }
  1216. // 13.2.7.3 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-regular-expression-literals-runtime-semantics-evaluation
  1217. inline Value new_regexp(VM& vm, ParsedRegex const& parsed_regex, ByteString const& pattern, ByteString const& flags)
  1218. {
  1219. // 1. Let pattern be CodePointsToString(BodyText of RegularExpressionLiteral).
  1220. // 2. Let flags be CodePointsToString(FlagText of RegularExpressionLiteral).
  1221. // 3. Return ! RegExpCreate(pattern, flags).
  1222. auto& realm = *vm.current_realm();
  1223. Regex<ECMA262> regex(parsed_regex.regex, parsed_regex.pattern, parsed_regex.flags);
  1224. // NOTE: We bypass RegExpCreate and subsequently RegExpAlloc as an optimization to use the already parsed values.
  1225. auto regexp_object = RegExpObject::create(realm, move(regex), pattern, flags);
  1226. // RegExpAlloc has these two steps from the 'Legacy RegExp features' proposal.
  1227. regexp_object->set_realm(realm);
  1228. // We don't need to check 'If SameValue(newTarget, thisRealm.[[Intrinsics]].[[%RegExp%]]) is true'
  1229. // here as we know RegExpCreate calls RegExpAlloc with %RegExp% for newTarget.
  1230. regexp_object->set_legacy_features_enabled(true);
  1231. return regexp_object;
  1232. }
  1233. // 13.3.8.1 https://tc39.es/ecma262/#sec-runtime-semantics-argumentlistevaluation
  1234. inline MarkedVector<Value> argument_list_evaluation(VM& vm, Value arguments)
  1235. {
  1236. // Note: Any spreading and actual evaluation is handled in preceding opcodes
  1237. // Note: The spec uses the concept of a list, while we create a temporary array
  1238. // in the preceding opcodes, so we have to convert in a manner that is not
  1239. // visible to the user
  1240. MarkedVector<Value> argument_values { vm.heap() };
  1241. auto& argument_array = arguments.as_array();
  1242. auto array_length = argument_array.indexed_properties().array_like_size();
  1243. argument_values.ensure_capacity(array_length);
  1244. for (size_t i = 0; i < array_length; ++i) {
  1245. if (auto maybe_value = argument_array.indexed_properties().get(i); maybe_value.has_value())
  1246. argument_values.append(maybe_value.release_value().value);
  1247. else
  1248. argument_values.append(js_undefined());
  1249. }
  1250. return argument_values;
  1251. }
  1252. inline ThrowCompletionOr<void> create_variable(VM& vm, DeprecatedFlyString const& name, Op::EnvironmentMode mode, bool is_global, bool is_immutable, bool is_strict)
  1253. {
  1254. if (mode == Op::EnvironmentMode::Lexical) {
  1255. VERIFY(!is_global);
  1256. // Note: This is papering over an issue where "FunctionDeclarationInstantiation" creates these bindings for us.
  1257. // Instead of crashing in there, we'll just raise an exception here.
  1258. if (TRY(vm.lexical_environment()->has_binding(name)))
  1259. return vm.throw_completion<InternalError>(TRY_OR_THROW_OOM(vm, String::formatted("Lexical environment already has binding '{}'", name)));
  1260. if (is_immutable)
  1261. return vm.lexical_environment()->create_immutable_binding(vm, name, is_strict);
  1262. return vm.lexical_environment()->create_mutable_binding(vm, name, is_strict);
  1263. }
  1264. if (!is_global) {
  1265. if (is_immutable)
  1266. return vm.variable_environment()->create_immutable_binding(vm, name, is_strict);
  1267. return vm.variable_environment()->create_mutable_binding(vm, name, is_strict);
  1268. }
  1269. // NOTE: CreateVariable with m_is_global set to true is expected to only be used in GlobalDeclarationInstantiation currently, which only uses "false" for "can_be_deleted".
  1270. // The only area that sets "can_be_deleted" to true is EvalDeclarationInstantiation, which is currently fully implemented in C++ and not in Bytecode.
  1271. return verify_cast<GlobalEnvironment>(vm.variable_environment())->create_global_var_binding(name, false);
  1272. }
  1273. inline ThrowCompletionOr<ECMAScriptFunctionObject*> new_class(VM& vm, Value super_class, ClassExpression const& class_expression, Optional<IdentifierTableIndex> const& lhs_name, ReadonlySpan<Value> element_keys)
  1274. {
  1275. auto& interpreter = vm.bytecode_interpreter();
  1276. auto name = class_expression.name();
  1277. // NOTE: NewClass expects classEnv to be active lexical environment
  1278. auto* class_environment = vm.lexical_environment();
  1279. vm.running_execution_context().lexical_environment = vm.running_execution_context().saved_lexical_environments.take_last();
  1280. Optional<DeprecatedFlyString> binding_name;
  1281. DeprecatedFlyString class_name;
  1282. if (!class_expression.has_name() && lhs_name.has_value()) {
  1283. class_name = interpreter.current_executable().get_identifier(lhs_name.value());
  1284. } else {
  1285. binding_name = name;
  1286. class_name = name.is_null() ? ""sv : name;
  1287. }
  1288. return TRY(class_expression.create_class_constructor(vm, class_environment, vm.lexical_environment(), super_class, element_keys, binding_name, class_name));
  1289. }
  1290. // 13.3.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  1291. inline ThrowCompletionOr<NonnullGCPtr<Object>> super_call_with_argument_array(VM& vm, Value argument_array, bool is_synthetic)
  1292. {
  1293. // 1. Let newTarget be GetNewTarget().
  1294. auto new_target = vm.get_new_target();
  1295. // 2. Assert: Type(newTarget) is Object.
  1296. VERIFY(new_target.is_object());
  1297. // 3. Let func be GetSuperConstructor().
  1298. auto* func = get_super_constructor(vm);
  1299. // 4. Let argList be ? ArgumentListEvaluation of Arguments.
  1300. MarkedVector<Value> arg_list { vm.heap() };
  1301. if (is_synthetic) {
  1302. VERIFY(argument_array.is_object() && is<Array>(argument_array.as_object()));
  1303. auto const& array_value = static_cast<Array const&>(argument_array.as_object());
  1304. auto length = MUST(length_of_array_like(vm, array_value));
  1305. for (size_t i = 0; i < length; ++i)
  1306. arg_list.append(array_value.get_without_side_effects(PropertyKey { i }));
  1307. } else {
  1308. arg_list = argument_list_evaluation(vm, argument_array);
  1309. }
  1310. // 5. If IsConstructor(func) is false, throw a TypeError exception.
  1311. if (!Value(func).is_constructor())
  1312. return vm.throw_completion<TypeError>(ErrorType::NotAConstructor, "Super constructor");
  1313. // 6. Let result be ? Construct(func, argList, newTarget).
  1314. auto result = TRY(construct(vm, static_cast<FunctionObject&>(*func), arg_list.span(), &new_target.as_function()));
  1315. // 7. Let thisER be GetThisEnvironment().
  1316. auto& this_environment = verify_cast<FunctionEnvironment>(*get_this_environment(vm));
  1317. // 8. Perform ? thisER.BindThisValue(result).
  1318. TRY(this_environment.bind_this_value(vm, result));
  1319. // 9. Let F be thisER.[[FunctionObject]].
  1320. auto& f = this_environment.function_object();
  1321. // 10. Assert: F is an ECMAScript function object.
  1322. // NOTE: This is implied by the strong C++ type.
  1323. // 11. Perform ? InitializeInstanceElements(result, F).
  1324. TRY(result->initialize_instance_elements(f));
  1325. // 12. Return result.
  1326. return result;
  1327. }
  1328. inline ThrowCompletionOr<NonnullGCPtr<Array>> iterator_to_array(VM& vm, Value iterator)
  1329. {
  1330. auto& iterator_record = verify_cast<IteratorRecord>(iterator.as_object());
  1331. auto array = MUST(Array::create(*vm.current_realm(), 0));
  1332. size_t index = 0;
  1333. while (true) {
  1334. auto value = TRY(iterator_step_value(vm, iterator_record));
  1335. if (!value.has_value())
  1336. return array;
  1337. MUST(array->create_data_property_or_throw(index, value.release_value()));
  1338. index++;
  1339. }
  1340. }
  1341. inline ThrowCompletionOr<void> append(VM& vm, Value lhs, Value rhs, bool is_spread)
  1342. {
  1343. // Note: This OpCode is used to construct array literals and argument arrays for calls,
  1344. // containing at least one spread element,
  1345. // Iterating over such a spread element to unpack it has to be visible by
  1346. // the user courtesy of
  1347. // (1) https://tc39.es/ecma262/#sec-runtime-semantics-arrayaccumulation
  1348. // SpreadElement : ... AssignmentExpression
  1349. // 1. Let spreadRef be ? Evaluation of AssignmentExpression.
  1350. // 2. Let spreadObj be ? GetValue(spreadRef).
  1351. // 3. Let iteratorRecord be ? GetIterator(spreadObj).
  1352. // 4. Repeat,
  1353. // a. Let next be ? IteratorStep(iteratorRecord).
  1354. // b. If next is false, return nextIndex.
  1355. // c. Let nextValue be ? IteratorValue(next).
  1356. // d. Perform ! CreateDataPropertyOrThrow(array, ! ToString(𝔽(nextIndex)), nextValue).
  1357. // e. Set nextIndex to nextIndex + 1.
  1358. // (2) https://tc39.es/ecma262/#sec-runtime-semantics-argumentlistevaluation
  1359. // ArgumentList : ... AssignmentExpression
  1360. // 1. Let list be a new empty List.
  1361. // 2. Let spreadRef be ? Evaluation of AssignmentExpression.
  1362. // 3. Let spreadObj be ? GetValue(spreadRef).
  1363. // 4. Let iteratorRecord be ? GetIterator(spreadObj).
  1364. // 5. Repeat,
  1365. // a. Let next be ? IteratorStep(iteratorRecord).
  1366. // b. If next is false, return list.
  1367. // c. Let nextArg be ? IteratorValue(next).
  1368. // d. Append nextArg to list.
  1369. // ArgumentList : ArgumentList , ... AssignmentExpression
  1370. // 1. Let precedingArgs be ? ArgumentListEvaluation of ArgumentList.
  1371. // 2. Let spreadRef be ? Evaluation of AssignmentExpression.
  1372. // 3. Let iteratorRecord be ? GetIterator(? GetValue(spreadRef)).
  1373. // 4. Repeat,
  1374. // a. Let next be ? IteratorStep(iteratorRecord).
  1375. // b. If next is false, return precedingArgs.
  1376. // c. Let nextArg be ? IteratorValue(next).
  1377. // d. Append nextArg to precedingArgs.
  1378. // Note: We know from codegen, that lhs is a plain array with only indexed properties
  1379. auto& lhs_array = lhs.as_array();
  1380. auto lhs_size = lhs_array.indexed_properties().array_like_size();
  1381. if (is_spread) {
  1382. // ...rhs
  1383. size_t i = lhs_size;
  1384. TRY(get_iterator_values(vm, rhs, [&i, &lhs_array](Value iterator_value) -> Optional<Completion> {
  1385. lhs_array.indexed_properties().put(i, iterator_value, default_attributes);
  1386. ++i;
  1387. return {};
  1388. }));
  1389. } else {
  1390. lhs_array.indexed_properties().put(lhs_size, rhs, default_attributes);
  1391. }
  1392. return {};
  1393. }
  1394. inline ThrowCompletionOr<Value> delete_by_id(Bytecode::Interpreter& interpreter, Value base, IdentifierTableIndex property)
  1395. {
  1396. auto& vm = interpreter.vm();
  1397. auto const& identifier = interpreter.current_executable().get_identifier(property);
  1398. bool strict = vm.in_strict_mode();
  1399. auto reference = Reference { base, identifier, {}, strict };
  1400. return TRY(reference.delete_(vm));
  1401. }
  1402. inline ThrowCompletionOr<Value> delete_by_value(Bytecode::Interpreter& interpreter, Value base, Value property_key_value)
  1403. {
  1404. auto& vm = interpreter.vm();
  1405. auto property_key = TRY(property_key_value.to_property_key(vm));
  1406. bool strict = vm.in_strict_mode();
  1407. auto reference = Reference { base, property_key, {}, strict };
  1408. return Value(TRY(reference.delete_(vm)));
  1409. }
  1410. inline ThrowCompletionOr<Value> delete_by_value_with_this(Bytecode::Interpreter& interpreter, Value base, Value property_key_value, Value this_value)
  1411. {
  1412. auto& vm = interpreter.vm();
  1413. auto property_key = TRY(property_key_value.to_property_key(vm));
  1414. bool strict = vm.in_strict_mode();
  1415. auto reference = Reference { base, property_key, this_value, strict };
  1416. return Value(TRY(reference.delete_(vm)));
  1417. }
  1418. // 14.7.5.9 EnumerateObjectProperties ( O ), https://tc39.es/ecma262/#sec-enumerate-object-properties
  1419. inline ThrowCompletionOr<Object*> get_object_property_iterator(VM& vm, Value value)
  1420. {
  1421. // While the spec does provide an algorithm, it allows us to implement it ourselves so long as we meet the following invariants:
  1422. // 1- Returned property keys do not include keys that are Symbols
  1423. // 2- Properties of the target object may be deleted during enumeration. A property that is deleted before it is processed by the iterator's next method is ignored
  1424. // 3- If new properties are added to the target object during enumeration, the newly added properties are not guaranteed to be processed in the active enumeration
  1425. // 4- A property name will be returned by the iterator's next method at most once in any enumeration.
  1426. // 5- Enumerating the properties of the target object includes enumerating properties of its prototype, and the prototype of the prototype, and so on, recursively;
  1427. // but a property of a prototype is not processed if it has the same name as a property that has already been processed by the iterator's next method.
  1428. // 6- The values of [[Enumerable]] attributes are not considered when determining if a property of a prototype object has already been processed.
  1429. // 7- The enumerable property names of prototype objects must be obtained by invoking EnumerateObjectProperties passing the prototype object as the argument.
  1430. // 8- EnumerateObjectProperties must obtain the own property keys of the target object by calling its [[OwnPropertyKeys]] internal method.
  1431. // 9- Property attributes of the target object must be obtained by calling its [[GetOwnProperty]] internal method
  1432. // Invariant 3 effectively allows the implementation to ignore newly added keys, and we do so (similar to other implementations).
  1433. auto object = TRY(value.to_object(vm));
  1434. // Note: While the spec doesn't explicitly require these to be ordered, it says that the values should be retrieved via OwnPropertyKeys,
  1435. // so we just keep the order consistent anyway.
  1436. OrderedHashTable<PropertyKey> properties;
  1437. OrderedHashTable<PropertyKey> non_enumerable_properties;
  1438. HashTable<NonnullGCPtr<Object>> seen_objects;
  1439. // Collect all keys immediately (invariant no. 5)
  1440. for (auto object_to_check = GCPtr { object.ptr() }; object_to_check && !seen_objects.contains(*object_to_check); object_to_check = TRY(object_to_check->internal_get_prototype_of())) {
  1441. seen_objects.set(*object_to_check);
  1442. for (auto& key : TRY(object_to_check->internal_own_property_keys())) {
  1443. if (key.is_symbol())
  1444. continue;
  1445. auto property_key = TRY(PropertyKey::from_value(vm, key));
  1446. // If there is a non-enumerable property higher up the prototype chain with the same key,
  1447. // we mustn't include this property even if it's enumerable (invariant no. 5 and 6)
  1448. if (non_enumerable_properties.contains(property_key))
  1449. continue;
  1450. if (properties.contains(property_key))
  1451. continue;
  1452. auto descriptor = TRY(object_to_check->internal_get_own_property(property_key));
  1453. if (!*descriptor->enumerable)
  1454. non_enumerable_properties.set(move(property_key));
  1455. else
  1456. properties.set(move(property_key));
  1457. }
  1458. }
  1459. auto& realm = *vm.current_realm();
  1460. auto callback = NativeFunction::create(
  1461. *vm.current_realm(), [items = move(properties)](VM& vm) mutable -> ThrowCompletionOr<Value> {
  1462. auto& realm = *vm.current_realm();
  1463. auto iterated_object_value = vm.this_value();
  1464. if (!iterated_object_value.is_object())
  1465. return vm.throw_completion<InternalError>("Invalid state for GetObjectPropertyIterator.next"sv);
  1466. auto& iterated_object = iterated_object_value.as_object();
  1467. auto result_object = Object::create(realm, nullptr);
  1468. while (true) {
  1469. if (items.is_empty()) {
  1470. result_object->define_direct_property(vm.names.done, JS::Value(true), default_attributes);
  1471. return result_object;
  1472. }
  1473. auto key = items.take_first();
  1474. // If the property is deleted, don't include it (invariant no. 2)
  1475. if (!TRY(iterated_object.has_property(key)))
  1476. continue;
  1477. result_object->define_direct_property(vm.names.done, JS::Value(false), default_attributes);
  1478. if (key.is_number())
  1479. result_object->define_direct_property(vm.names.value, PrimitiveString::create(vm, String::number(key.as_number())), default_attributes);
  1480. else if (key.is_string())
  1481. result_object->define_direct_property(vm.names.value, PrimitiveString::create(vm, key.as_string()), default_attributes);
  1482. else
  1483. VERIFY_NOT_REACHED(); // We should not have non-string/number keys.
  1484. return result_object;
  1485. }
  1486. },
  1487. 1, vm.names.next);
  1488. return vm.heap().allocate<IteratorRecord>(realm, realm, object, callback, false).ptr();
  1489. }
  1490. ByteString Instruction::to_byte_string(Bytecode::Executable const& executable) const
  1491. {
  1492. #define __BYTECODE_OP(op) \
  1493. case Instruction::Type::op: \
  1494. return static_cast<Bytecode::Op::op const&>(*this).to_byte_string_impl(executable);
  1495. switch (type()) {
  1496. ENUMERATE_BYTECODE_OPS(__BYTECODE_OP)
  1497. default:
  1498. VERIFY_NOT_REACHED();
  1499. }
  1500. #undef __BYTECODE_OP
  1501. }
  1502. }
  1503. namespace JS::Bytecode::Op {
  1504. static void dump_object(Object& o, HashTable<Object const*>& seen, int indent = 0)
  1505. {
  1506. if (seen.contains(&o))
  1507. return;
  1508. seen.set(&o);
  1509. for (auto& it : o.shape().property_table()) {
  1510. auto value = o.get_direct(it.value.offset);
  1511. dbgln("{} {} -> {}", String::repeated(' ', indent).release_value(), it.key.to_display_string(), value);
  1512. if (value.is_object()) {
  1513. dump_object(value.as_object(), seen, indent + 2);
  1514. }
  1515. }
  1516. }
  1517. void Dump::execute_impl(Bytecode::Interpreter& interpreter) const
  1518. {
  1519. auto value = interpreter.get(m_value);
  1520. dbgln("(DUMP) {}: {}", m_text, value);
  1521. if (value.is_object()) {
  1522. HashTable<Object const*> seen;
  1523. dump_object(value.as_object(), seen);
  1524. }
  1525. }
  1526. #define JS_DEFINE_EXECUTE_FOR_COMMON_BINARY_OP(OpTitleCase, op_snake_case) \
  1527. ThrowCompletionOr<void> OpTitleCase::execute_impl(Bytecode::Interpreter& interpreter) const \
  1528. { \
  1529. auto& vm = interpreter.vm(); \
  1530. auto lhs = interpreter.get(m_lhs); \
  1531. auto rhs = interpreter.get(m_rhs); \
  1532. interpreter.set(m_dst, TRY(op_snake_case(vm, lhs, rhs))); \
  1533. return {}; \
  1534. }
  1535. #define JS_DEFINE_TO_BYTE_STRING_FOR_COMMON_BINARY_OP(OpTitleCase, op_snake_case) \
  1536. ByteString OpTitleCase::to_byte_string_impl(Bytecode::Executable const& executable) const \
  1537. { \
  1538. return ByteString::formatted(#OpTitleCase " {}, {}, {}", \
  1539. format_operand("dst"sv, m_dst, executable), \
  1540. format_operand("lhs"sv, m_lhs, executable), \
  1541. format_operand("rhs"sv, m_rhs, executable)); \
  1542. }
  1543. JS_ENUMERATE_COMMON_BINARY_OPS_WITHOUT_FAST_PATH(JS_DEFINE_EXECUTE_FOR_COMMON_BINARY_OP)
  1544. JS_ENUMERATE_COMMON_BINARY_OPS_WITHOUT_FAST_PATH(JS_DEFINE_TO_BYTE_STRING_FOR_COMMON_BINARY_OP)
  1545. JS_ENUMERATE_COMMON_BINARY_OPS_WITH_FAST_PATH(JS_DEFINE_TO_BYTE_STRING_FOR_COMMON_BINARY_OP)
  1546. ThrowCompletionOr<void> Add::execute_impl(Bytecode::Interpreter& interpreter) const
  1547. {
  1548. auto& vm = interpreter.vm();
  1549. auto const lhs = interpreter.get(m_lhs);
  1550. auto const rhs = interpreter.get(m_rhs);
  1551. if (lhs.is_number() && rhs.is_number()) {
  1552. if (lhs.is_int32() && rhs.is_int32()) {
  1553. if (!Checked<i32>::addition_would_overflow(lhs.as_i32(), rhs.as_i32())) {
  1554. interpreter.set(m_dst, Value(lhs.as_i32() + rhs.as_i32()));
  1555. return {};
  1556. }
  1557. }
  1558. interpreter.set(m_dst, Value(lhs.as_double() + rhs.as_double()));
  1559. return {};
  1560. }
  1561. interpreter.set(m_dst, TRY(add(vm, lhs, rhs)));
  1562. return {};
  1563. }
  1564. ThrowCompletionOr<void> Mul::execute_impl(Bytecode::Interpreter& interpreter) const
  1565. {
  1566. auto& vm = interpreter.vm();
  1567. auto const lhs = interpreter.get(m_lhs);
  1568. auto const rhs = interpreter.get(m_rhs);
  1569. if (lhs.is_number() && rhs.is_number()) {
  1570. if (lhs.is_int32() && rhs.is_int32()) {
  1571. if (!Checked<i32>::multiplication_would_overflow(lhs.as_i32(), rhs.as_i32())) {
  1572. interpreter.set(m_dst, Value(lhs.as_i32() * rhs.as_i32()));
  1573. return {};
  1574. }
  1575. }
  1576. interpreter.set(m_dst, Value(lhs.as_double() * rhs.as_double()));
  1577. return {};
  1578. }
  1579. interpreter.set(m_dst, TRY(mul(vm, lhs, rhs)));
  1580. return {};
  1581. }
  1582. ThrowCompletionOr<void> Sub::execute_impl(Bytecode::Interpreter& interpreter) const
  1583. {
  1584. auto& vm = interpreter.vm();
  1585. auto const lhs = interpreter.get(m_lhs);
  1586. auto const rhs = interpreter.get(m_rhs);
  1587. if (lhs.is_number() && rhs.is_number()) {
  1588. if (lhs.is_int32() && rhs.is_int32()) {
  1589. if (!Checked<i32>::subtraction_would_overflow(lhs.as_i32(), rhs.as_i32())) {
  1590. interpreter.set(m_dst, Value(lhs.as_i32() - rhs.as_i32()));
  1591. return {};
  1592. }
  1593. }
  1594. interpreter.set(m_dst, Value(lhs.as_double() - rhs.as_double()));
  1595. return {};
  1596. }
  1597. interpreter.set(m_dst, TRY(sub(vm, lhs, rhs)));
  1598. return {};
  1599. }
  1600. ThrowCompletionOr<void> BitwiseXor::execute_impl(Bytecode::Interpreter& interpreter) const
  1601. {
  1602. auto& vm = interpreter.vm();
  1603. auto const lhs = interpreter.get(m_lhs);
  1604. auto const rhs = interpreter.get(m_rhs);
  1605. if (lhs.is_int32() && rhs.is_int32()) {
  1606. interpreter.set(m_dst, Value(lhs.as_i32() ^ rhs.as_i32()));
  1607. return {};
  1608. }
  1609. interpreter.set(m_dst, TRY(bitwise_xor(vm, lhs, rhs)));
  1610. return {};
  1611. }
  1612. ThrowCompletionOr<void> BitwiseAnd::execute_impl(Bytecode::Interpreter& interpreter) const
  1613. {
  1614. auto& vm = interpreter.vm();
  1615. auto const lhs = interpreter.get(m_lhs);
  1616. auto const rhs = interpreter.get(m_rhs);
  1617. if (lhs.is_int32() && rhs.is_int32()) {
  1618. interpreter.set(m_dst, Value(lhs.as_i32() & rhs.as_i32()));
  1619. return {};
  1620. }
  1621. interpreter.set(m_dst, TRY(bitwise_and(vm, lhs, rhs)));
  1622. return {};
  1623. }
  1624. ThrowCompletionOr<void> BitwiseOr::execute_impl(Bytecode::Interpreter& interpreter) const
  1625. {
  1626. auto& vm = interpreter.vm();
  1627. auto const lhs = interpreter.get(m_lhs);
  1628. auto const rhs = interpreter.get(m_rhs);
  1629. if (lhs.is_int32() && rhs.is_int32()) {
  1630. interpreter.set(m_dst, Value(lhs.as_i32() | rhs.as_i32()));
  1631. return {};
  1632. }
  1633. interpreter.set(m_dst, TRY(bitwise_or(vm, lhs, rhs)));
  1634. return {};
  1635. }
  1636. ThrowCompletionOr<void> UnsignedRightShift::execute_impl(Bytecode::Interpreter& interpreter) const
  1637. {
  1638. auto& vm = interpreter.vm();
  1639. auto const lhs = interpreter.get(m_lhs);
  1640. auto const rhs = interpreter.get(m_rhs);
  1641. if (lhs.is_int32() && rhs.is_int32()) {
  1642. auto const shift_count = static_cast<u32>(rhs.as_i32()) % 32;
  1643. interpreter.set(m_dst, Value(static_cast<u32>(lhs.as_i32()) >> shift_count));
  1644. return {};
  1645. }
  1646. interpreter.set(m_dst, TRY(unsigned_right_shift(vm, lhs, rhs)));
  1647. return {};
  1648. }
  1649. ThrowCompletionOr<void> RightShift::execute_impl(Bytecode::Interpreter& interpreter) const
  1650. {
  1651. auto& vm = interpreter.vm();
  1652. auto const lhs = interpreter.get(m_lhs);
  1653. auto const rhs = interpreter.get(m_rhs);
  1654. if (lhs.is_int32() && rhs.is_int32()) {
  1655. auto const shift_count = static_cast<u32>(rhs.as_i32()) % 32;
  1656. interpreter.set(m_dst, Value(lhs.as_i32() >> shift_count));
  1657. return {};
  1658. }
  1659. interpreter.set(m_dst, TRY(right_shift(vm, lhs, rhs)));
  1660. return {};
  1661. }
  1662. ThrowCompletionOr<void> LeftShift::execute_impl(Bytecode::Interpreter& interpreter) const
  1663. {
  1664. auto& vm = interpreter.vm();
  1665. auto const lhs = interpreter.get(m_lhs);
  1666. auto const rhs = interpreter.get(m_rhs);
  1667. if (lhs.is_int32() && rhs.is_int32()) {
  1668. auto const shift_count = static_cast<u32>(rhs.as_i32()) % 32;
  1669. interpreter.set(m_dst, Value(lhs.as_i32() << shift_count));
  1670. return {};
  1671. }
  1672. interpreter.set(m_dst, TRY(left_shift(vm, lhs, rhs)));
  1673. return {};
  1674. }
  1675. ThrowCompletionOr<void> LessThan::execute_impl(Bytecode::Interpreter& interpreter) const
  1676. {
  1677. auto& vm = interpreter.vm();
  1678. auto const lhs = interpreter.get(m_lhs);
  1679. auto const rhs = interpreter.get(m_rhs);
  1680. if (lhs.is_number() && rhs.is_number()) {
  1681. if (lhs.is_int32() && rhs.is_int32()) {
  1682. interpreter.set(m_dst, Value(lhs.as_i32() < rhs.as_i32()));
  1683. return {};
  1684. }
  1685. interpreter.set(m_dst, Value(lhs.as_double() < rhs.as_double()));
  1686. return {};
  1687. }
  1688. interpreter.set(m_dst, TRY(less_than(vm, lhs, rhs)));
  1689. return {};
  1690. }
  1691. ThrowCompletionOr<void> LessThanEquals::execute_impl(Bytecode::Interpreter& interpreter) const
  1692. {
  1693. auto& vm = interpreter.vm();
  1694. auto const lhs = interpreter.get(m_lhs);
  1695. auto const rhs = interpreter.get(m_rhs);
  1696. if (lhs.is_number() && rhs.is_number()) {
  1697. if (lhs.is_int32() && rhs.is_int32()) {
  1698. interpreter.set(m_dst, Value(lhs.as_i32() <= rhs.as_i32()));
  1699. return {};
  1700. }
  1701. interpreter.set(m_dst, Value(lhs.as_double() <= rhs.as_double()));
  1702. return {};
  1703. }
  1704. interpreter.set(m_dst, TRY(less_than_equals(vm, lhs, rhs)));
  1705. return {};
  1706. }
  1707. ThrowCompletionOr<void> GreaterThan::execute_impl(Bytecode::Interpreter& interpreter) const
  1708. {
  1709. auto& vm = interpreter.vm();
  1710. auto const lhs = interpreter.get(m_lhs);
  1711. auto const rhs = interpreter.get(m_rhs);
  1712. if (lhs.is_number() && rhs.is_number()) {
  1713. if (lhs.is_int32() && rhs.is_int32()) {
  1714. interpreter.set(m_dst, Value(lhs.as_i32() > rhs.as_i32()));
  1715. return {};
  1716. }
  1717. interpreter.set(m_dst, Value(lhs.as_double() > rhs.as_double()));
  1718. return {};
  1719. }
  1720. interpreter.set(m_dst, TRY(greater_than(vm, lhs, rhs)));
  1721. return {};
  1722. }
  1723. ThrowCompletionOr<void> GreaterThanEquals::execute_impl(Bytecode::Interpreter& interpreter) const
  1724. {
  1725. auto& vm = interpreter.vm();
  1726. auto const lhs = interpreter.get(m_lhs);
  1727. auto const rhs = interpreter.get(m_rhs);
  1728. if (lhs.is_number() && rhs.is_number()) {
  1729. if (lhs.is_int32() && rhs.is_int32()) {
  1730. interpreter.set(m_dst, Value(lhs.as_i32() >= rhs.as_i32()));
  1731. return {};
  1732. }
  1733. interpreter.set(m_dst, Value(lhs.as_double() >= rhs.as_double()));
  1734. return {};
  1735. }
  1736. interpreter.set(m_dst, TRY(greater_than_equals(vm, lhs, rhs)));
  1737. return {};
  1738. }
  1739. static ThrowCompletionOr<Value> not_(VM&, Value value)
  1740. {
  1741. return Value(!value.to_boolean());
  1742. }
  1743. static ThrowCompletionOr<Value> typeof_(VM& vm, Value value)
  1744. {
  1745. return value.typeof_(vm);
  1746. }
  1747. #define JS_DEFINE_COMMON_UNARY_OP(OpTitleCase, op_snake_case) \
  1748. ThrowCompletionOr<void> OpTitleCase::execute_impl(Bytecode::Interpreter& interpreter) const \
  1749. { \
  1750. auto& vm = interpreter.vm(); \
  1751. interpreter.set(dst(), TRY(op_snake_case(vm, interpreter.get(src())))); \
  1752. return {}; \
  1753. } \
  1754. ByteString OpTitleCase::to_byte_string_impl(Bytecode::Executable const& executable) const \
  1755. { \
  1756. return ByteString::formatted(#OpTitleCase " {}, {}", \
  1757. format_operand("dst"sv, dst(), executable), \
  1758. format_operand("src"sv, src(), executable)); \
  1759. }
  1760. JS_ENUMERATE_COMMON_UNARY_OPS(JS_DEFINE_COMMON_UNARY_OP)
  1761. void NewArray::execute_impl(Bytecode::Interpreter& interpreter) const
  1762. {
  1763. auto array = MUST(Array::create(interpreter.realm(), 0));
  1764. for (size_t i = 0; i < m_element_count; i++) {
  1765. array->indexed_properties().put(i, interpreter.get(m_elements[i]), default_attributes);
  1766. }
  1767. interpreter.set(dst(), array);
  1768. }
  1769. void NewPrimitiveArray::execute_impl(Bytecode::Interpreter& interpreter) const
  1770. {
  1771. auto array = MUST(Array::create(interpreter.realm(), 0));
  1772. for (size_t i = 0; i < m_element_count; i++)
  1773. array->indexed_properties().put(i, m_elements[i], default_attributes);
  1774. interpreter.set(dst(), array);
  1775. }
  1776. void AddPrivateName::execute_impl(Bytecode::Interpreter& interpreter) const
  1777. {
  1778. auto const& name = interpreter.current_executable().get_identifier(m_name);
  1779. interpreter.vm().running_execution_context().private_environment->add_private_name(name);
  1780. }
  1781. ThrowCompletionOr<void> ArrayAppend::execute_impl(Bytecode::Interpreter& interpreter) const
  1782. {
  1783. return append(interpreter.vm(), interpreter.get(dst()), interpreter.get(src()), m_is_spread);
  1784. }
  1785. ThrowCompletionOr<void> ImportCall::execute_impl(Bytecode::Interpreter& interpreter) const
  1786. {
  1787. auto& vm = interpreter.vm();
  1788. auto specifier = interpreter.get(m_specifier);
  1789. auto options_value = interpreter.get(m_options);
  1790. interpreter.set(dst(), TRY(perform_import_call(vm, specifier, options_value)));
  1791. return {};
  1792. }
  1793. ThrowCompletionOr<void> IteratorToArray::execute_impl(Bytecode::Interpreter& interpreter) const
  1794. {
  1795. interpreter.set(dst(), TRY(iterator_to_array(interpreter.vm(), interpreter.get(iterator()))));
  1796. return {};
  1797. }
  1798. void NewObject::execute_impl(Bytecode::Interpreter& interpreter) const
  1799. {
  1800. auto& vm = interpreter.vm();
  1801. auto& realm = *vm.current_realm();
  1802. interpreter.set(dst(), Object::create(realm, realm.intrinsics().object_prototype()));
  1803. }
  1804. void NewRegExp::execute_impl(Bytecode::Interpreter& interpreter) const
  1805. {
  1806. interpreter.set(dst(),
  1807. new_regexp(
  1808. interpreter.vm(),
  1809. interpreter.current_executable().regex_table->get(m_regex_index),
  1810. interpreter.current_executable().get_string(m_source_index),
  1811. interpreter.current_executable().get_string(m_flags_index)));
  1812. }
  1813. #define JS_DEFINE_NEW_BUILTIN_ERROR_OP(ErrorName) \
  1814. void New##ErrorName::execute_impl(Bytecode::Interpreter& interpreter) const \
  1815. { \
  1816. auto& vm = interpreter.vm(); \
  1817. auto& realm = *vm.current_realm(); \
  1818. interpreter.set(dst(), ErrorName::create(realm, interpreter.current_executable().get_string(m_error_string))); \
  1819. } \
  1820. ByteString New##ErrorName::to_byte_string_impl(Bytecode::Executable const& executable) const \
  1821. { \
  1822. return ByteString::formatted("New" #ErrorName " {}, {}", \
  1823. format_operand("dst"sv, m_dst, executable), \
  1824. executable.string_table->get(m_error_string)); \
  1825. }
  1826. JS_ENUMERATE_NEW_BUILTIN_ERROR_OPS(JS_DEFINE_NEW_BUILTIN_ERROR_OP)
  1827. ThrowCompletionOr<void> CopyObjectExcludingProperties::execute_impl(Bytecode::Interpreter& interpreter) const
  1828. {
  1829. auto& vm = interpreter.vm();
  1830. auto& realm = *vm.current_realm();
  1831. auto from_object = interpreter.get(m_from_object);
  1832. auto to_object = Object::create(realm, realm.intrinsics().object_prototype());
  1833. HashTable<PropertyKey> excluded_names;
  1834. for (size_t i = 0; i < m_excluded_names_count; ++i) {
  1835. excluded_names.set(TRY(interpreter.get(m_excluded_names[i]).to_property_key(vm)));
  1836. }
  1837. TRY(to_object->copy_data_properties(vm, from_object, excluded_names));
  1838. interpreter.set(dst(), to_object);
  1839. return {};
  1840. }
  1841. ThrowCompletionOr<void> ConcatString::execute_impl(Bytecode::Interpreter& interpreter) const
  1842. {
  1843. auto& vm = interpreter.vm();
  1844. auto string = TRY(interpreter.get(src()).to_primitive_string(vm));
  1845. interpreter.set(dst(), PrimitiveString::create(vm, interpreter.get(dst()).as_string(), string));
  1846. return {};
  1847. }
  1848. ThrowCompletionOr<void> GetBinding::execute_impl(Bytecode::Interpreter& interpreter) const
  1849. {
  1850. auto& vm = interpreter.vm();
  1851. auto& executable = interpreter.current_executable();
  1852. if (m_cache.is_valid()) {
  1853. auto const* environment = interpreter.running_execution_context().lexical_environment.ptr();
  1854. for (size_t i = 0; i < m_cache.hops; ++i)
  1855. environment = environment->outer_environment();
  1856. if (!environment->is_permanently_screwed_by_eval()) {
  1857. interpreter.set(dst(), TRY(static_cast<DeclarativeEnvironment const&>(*environment).get_binding_value_direct(vm, m_cache.index)));
  1858. return {};
  1859. }
  1860. m_cache = {};
  1861. }
  1862. auto reference = TRY(vm.resolve_binding(executable.get_identifier(m_identifier)));
  1863. if (reference.environment_coordinate().has_value())
  1864. m_cache = reference.environment_coordinate().value();
  1865. interpreter.set(dst(), TRY(reference.get_value(vm)));
  1866. return {};
  1867. }
  1868. ThrowCompletionOr<void> GetCalleeAndThisFromEnvironment::execute_impl(Bytecode::Interpreter& interpreter) const
  1869. {
  1870. auto callee_and_this = TRY(get_callee_and_this_from_environment(
  1871. interpreter,
  1872. interpreter.current_executable().get_identifier(m_identifier),
  1873. m_cache));
  1874. interpreter.set(m_callee, callee_and_this.callee);
  1875. interpreter.set(m_this_value, callee_and_this.this_value);
  1876. return {};
  1877. }
  1878. ThrowCompletionOr<void> GetGlobal::execute_impl(Bytecode::Interpreter& interpreter) const
  1879. {
  1880. interpreter.set(dst(), TRY(get_global(interpreter, m_identifier, interpreter.current_executable().global_variable_caches[m_cache_index])));
  1881. return {};
  1882. }
  1883. ThrowCompletionOr<void> DeleteVariable::execute_impl(Bytecode::Interpreter& interpreter) const
  1884. {
  1885. auto& vm = interpreter.vm();
  1886. auto const& string = interpreter.current_executable().get_identifier(m_identifier);
  1887. auto reference = TRY(vm.resolve_binding(string));
  1888. interpreter.set(dst(), Value(TRY(reference.delete_(vm))));
  1889. return {};
  1890. }
  1891. void CreateLexicalEnvironment::execute_impl(Bytecode::Interpreter& interpreter) const
  1892. {
  1893. auto make_and_swap_envs = [&](auto& old_environment) {
  1894. auto declarative_environment = new_declarative_environment(*old_environment).ptr();
  1895. declarative_environment->ensure_capacity(m_capacity);
  1896. GCPtr<Environment> environment = declarative_environment;
  1897. swap(old_environment, environment);
  1898. return environment;
  1899. };
  1900. auto& running_execution_context = interpreter.running_execution_context();
  1901. running_execution_context.saved_lexical_environments.append(make_and_swap_envs(running_execution_context.lexical_environment));
  1902. }
  1903. void CreatePrivateEnvironment::execute_impl(Bytecode::Interpreter& interpreter) const
  1904. {
  1905. auto& running_execution_context = interpreter.vm().running_execution_context();
  1906. auto outer_private_environment = running_execution_context.private_environment;
  1907. running_execution_context.private_environment = new_private_environment(interpreter.vm(), outer_private_environment);
  1908. }
  1909. void CreateVariableEnvironment::execute_impl(Bytecode::Interpreter& interpreter) const
  1910. {
  1911. auto& running_execution_context = interpreter.running_execution_context();
  1912. auto var_environment = new_declarative_environment(*running_execution_context.lexical_environment);
  1913. var_environment->ensure_capacity(m_capacity);
  1914. running_execution_context.variable_environment = var_environment;
  1915. running_execution_context.lexical_environment = var_environment;
  1916. }
  1917. ThrowCompletionOr<void> EnterObjectEnvironment::execute_impl(Bytecode::Interpreter& interpreter) const
  1918. {
  1919. auto object = TRY(interpreter.get(m_object).to_object(interpreter.vm()));
  1920. interpreter.enter_object_environment(*object);
  1921. return {};
  1922. }
  1923. void Catch::execute_impl(Bytecode::Interpreter& interpreter) const
  1924. {
  1925. interpreter.catch_exception(dst());
  1926. }
  1927. void LeaveFinally::execute_impl(Bytecode::Interpreter& interpreter) const
  1928. {
  1929. interpreter.leave_finally();
  1930. }
  1931. void RestoreScheduledJump::execute_impl(Bytecode::Interpreter& interpreter) const
  1932. {
  1933. interpreter.restore_scheduled_jump();
  1934. }
  1935. ThrowCompletionOr<void> CreateVariable::execute_impl(Bytecode::Interpreter& interpreter) const
  1936. {
  1937. auto const& name = interpreter.current_executable().get_identifier(m_identifier);
  1938. return create_variable(interpreter.vm(), name, m_mode, m_is_global, m_is_immutable, m_is_strict);
  1939. }
  1940. ThrowCompletionOr<void> CreateRestParams::execute_impl(Bytecode::Interpreter& interpreter) const
  1941. {
  1942. auto const& arguments = interpreter.running_execution_context().arguments;
  1943. auto arguments_count = interpreter.running_execution_context().passed_argument_count;
  1944. auto array = MUST(Array::create(interpreter.realm(), 0));
  1945. for (size_t rest_index = m_rest_index; rest_index < arguments_count; ++rest_index)
  1946. array->indexed_properties().append(arguments[rest_index]);
  1947. interpreter.set(m_dst, array);
  1948. return {};
  1949. }
  1950. ThrowCompletionOr<void> CreateArguments::execute_impl(Bytecode::Interpreter& interpreter) const
  1951. {
  1952. auto const& function = interpreter.running_execution_context().function;
  1953. auto const& arguments = interpreter.running_execution_context().arguments;
  1954. auto const& environment = interpreter.running_execution_context().lexical_environment;
  1955. auto passed_arguments = ReadonlySpan<Value> { arguments.data(), interpreter.running_execution_context().passed_argument_count };
  1956. Object* arguments_object;
  1957. if (m_kind == Kind::Mapped) {
  1958. arguments_object = create_mapped_arguments_object(interpreter.vm(), *function, function->formal_parameters(), passed_arguments, *environment);
  1959. } else {
  1960. arguments_object = create_unmapped_arguments_object(interpreter.vm(), passed_arguments);
  1961. }
  1962. if (m_dst.has_value()) {
  1963. interpreter.set(*m_dst, arguments_object);
  1964. return {};
  1965. }
  1966. if (m_is_immutable) {
  1967. MUST(environment->create_immutable_binding(interpreter.vm(), interpreter.vm().names.arguments.as_string(), false));
  1968. } else {
  1969. MUST(environment->create_mutable_binding(interpreter.vm(), interpreter.vm().names.arguments.as_string(), false));
  1970. }
  1971. MUST(environment->initialize_binding(interpreter.vm(), interpreter.vm().names.arguments.as_string(), arguments_object, Environment::InitializeBindingHint::Normal));
  1972. return {};
  1973. }
  1974. template<EnvironmentMode environment_mode, BindingInitializationMode initialization_mode>
  1975. static ThrowCompletionOr<void> initialize_or_set_binding(Interpreter& interpreter, IdentifierTableIndex identifier_index, Value value, EnvironmentCoordinate& cache)
  1976. {
  1977. auto& vm = interpreter.vm();
  1978. auto* environment = environment_mode == EnvironmentMode::Lexical
  1979. ? interpreter.running_execution_context().lexical_environment.ptr()
  1980. : interpreter.running_execution_context().variable_environment.ptr();
  1981. if (cache.is_valid()) {
  1982. for (size_t i = 0; i < cache.hops; ++i)
  1983. environment = environment->outer_environment();
  1984. if (!environment->is_permanently_screwed_by_eval()) {
  1985. if constexpr (initialization_mode == BindingInitializationMode::Initialize) {
  1986. TRY(static_cast<DeclarativeEnvironment&>(*environment).initialize_binding_direct(vm, cache.index, value, Environment::InitializeBindingHint::Normal));
  1987. } else {
  1988. TRY(static_cast<DeclarativeEnvironment&>(*environment).set_mutable_binding_direct(vm, cache.index, value, vm.in_strict_mode()));
  1989. }
  1990. return {};
  1991. }
  1992. cache = {};
  1993. }
  1994. auto reference = TRY(vm.resolve_binding(interpreter.current_executable().get_identifier(identifier_index), environment));
  1995. if (reference.environment_coordinate().has_value())
  1996. cache = reference.environment_coordinate().value();
  1997. if constexpr (initialization_mode == BindingInitializationMode::Initialize) {
  1998. TRY(reference.initialize_referenced_binding(vm, value));
  1999. } else if (initialization_mode == BindingInitializationMode::Set) {
  2000. TRY(reference.put_value(vm, value));
  2001. }
  2002. return {};
  2003. }
  2004. ThrowCompletionOr<void> InitializeLexicalBinding::execute_impl(Bytecode::Interpreter& interpreter) const
  2005. {
  2006. return initialize_or_set_binding<EnvironmentMode::Lexical, BindingInitializationMode::Initialize>(interpreter, m_identifier, interpreter.get(m_src), m_cache);
  2007. }
  2008. ThrowCompletionOr<void> InitializeVariableBinding::execute_impl(Bytecode::Interpreter& interpreter) const
  2009. {
  2010. return initialize_or_set_binding<EnvironmentMode::Var, BindingInitializationMode::Initialize>(interpreter, m_identifier, interpreter.get(m_src), m_cache);
  2011. }
  2012. ThrowCompletionOr<void> SetLexicalBinding::execute_impl(Bytecode::Interpreter& interpreter) const
  2013. {
  2014. return initialize_or_set_binding<EnvironmentMode::Lexical, BindingInitializationMode::Set>(interpreter, m_identifier, interpreter.get(m_src), m_cache);
  2015. }
  2016. ThrowCompletionOr<void> SetVariableBinding::execute_impl(Bytecode::Interpreter& interpreter) const
  2017. {
  2018. return initialize_or_set_binding<EnvironmentMode::Var, BindingInitializationMode::Set>(interpreter, m_identifier, interpreter.get(m_src), m_cache);
  2019. }
  2020. ThrowCompletionOr<void> GetById::execute_impl(Bytecode::Interpreter& interpreter) const
  2021. {
  2022. auto base_value = interpreter.get(base());
  2023. auto& cache = interpreter.current_executable().property_lookup_caches[m_cache_index];
  2024. interpreter.set(dst(), TRY(get_by_id(interpreter.vm(), m_base_identifier, m_property, base_value, base_value, cache, interpreter.current_executable())));
  2025. return {};
  2026. }
  2027. ThrowCompletionOr<void> GetByIdWithThis::execute_impl(Bytecode::Interpreter& interpreter) const
  2028. {
  2029. auto base_value = interpreter.get(m_base);
  2030. auto this_value = interpreter.get(m_this_value);
  2031. auto& cache = interpreter.current_executable().property_lookup_caches[m_cache_index];
  2032. interpreter.set(dst(), TRY(get_by_id(interpreter.vm(), {}, m_property, base_value, this_value, cache, interpreter.current_executable())));
  2033. return {};
  2034. }
  2035. ThrowCompletionOr<void> GetLength::execute_impl(Bytecode::Interpreter& interpreter) const
  2036. {
  2037. auto base_value = interpreter.get(base());
  2038. auto& executable = interpreter.current_executable();
  2039. auto& cache = executable.property_lookup_caches[m_cache_index];
  2040. interpreter.set(dst(), TRY(get_by_id<GetByIdMode::Length>(interpreter.vm(), m_base_identifier, *executable.length_identifier, base_value, base_value, cache, executable)));
  2041. return {};
  2042. }
  2043. ThrowCompletionOr<void> GetLengthWithThis::execute_impl(Bytecode::Interpreter& interpreter) const
  2044. {
  2045. auto base_value = interpreter.get(m_base);
  2046. auto this_value = interpreter.get(m_this_value);
  2047. auto& executable = interpreter.current_executable();
  2048. auto& cache = executable.property_lookup_caches[m_cache_index];
  2049. interpreter.set(dst(), TRY(get_by_id<GetByIdMode::Length>(interpreter.vm(), {}, *executable.length_identifier, base_value, this_value, cache, executable)));
  2050. return {};
  2051. }
  2052. ThrowCompletionOr<void> GetPrivateById::execute_impl(Bytecode::Interpreter& interpreter) const
  2053. {
  2054. auto& vm = interpreter.vm();
  2055. auto const& name = interpreter.current_executable().get_identifier(m_property);
  2056. auto base_value = interpreter.get(m_base);
  2057. auto private_reference = make_private_reference(vm, base_value, name);
  2058. interpreter.set(dst(), TRY(private_reference.get_value(vm)));
  2059. return {};
  2060. }
  2061. ThrowCompletionOr<void> HasPrivateId::execute_impl(Bytecode::Interpreter& interpreter) const
  2062. {
  2063. auto& vm = interpreter.vm();
  2064. auto base = interpreter.get(m_base);
  2065. if (!base.is_object())
  2066. return vm.throw_completion<TypeError>(ErrorType::InOperatorWithObject);
  2067. auto private_environment = interpreter.running_execution_context().private_environment;
  2068. VERIFY(private_environment);
  2069. auto private_name = private_environment->resolve_private_identifier(interpreter.current_executable().get_identifier(m_property));
  2070. interpreter.set(dst(), Value(base.as_object().private_element_find(private_name) != nullptr));
  2071. return {};
  2072. }
  2073. ThrowCompletionOr<void> PutById::execute_impl(Bytecode::Interpreter& interpreter) const
  2074. {
  2075. auto& vm = interpreter.vm();
  2076. auto value = interpreter.get(m_src);
  2077. auto base = interpreter.get(m_base);
  2078. auto base_identifier = interpreter.current_executable().get_identifier(m_base_identifier);
  2079. PropertyKey name = interpreter.current_executable().get_identifier(m_property);
  2080. auto& cache = interpreter.current_executable().property_lookup_caches[m_cache_index];
  2081. TRY(put_by_property_key(vm, base, base, value, base_identifier, name, m_kind, &cache));
  2082. return {};
  2083. }
  2084. ThrowCompletionOr<void> PutByIdWithThis::execute_impl(Bytecode::Interpreter& interpreter) const
  2085. {
  2086. auto& vm = interpreter.vm();
  2087. auto value = interpreter.get(m_src);
  2088. auto base = interpreter.get(m_base);
  2089. PropertyKey name = interpreter.current_executable().get_identifier(m_property);
  2090. auto& cache = interpreter.current_executable().property_lookup_caches[m_cache_index];
  2091. TRY(put_by_property_key(vm, base, interpreter.get(m_this_value), value, {}, name, m_kind, &cache));
  2092. return {};
  2093. }
  2094. ThrowCompletionOr<void> PutPrivateById::execute_impl(Bytecode::Interpreter& interpreter) const
  2095. {
  2096. auto& vm = interpreter.vm();
  2097. auto value = interpreter.get(m_src);
  2098. auto object = TRY(interpreter.get(m_base).to_object(vm));
  2099. auto name = interpreter.current_executable().get_identifier(m_property);
  2100. auto private_reference = make_private_reference(vm, object, name);
  2101. TRY(private_reference.put_value(vm, value));
  2102. return {};
  2103. }
  2104. ThrowCompletionOr<void> DeleteById::execute_impl(Bytecode::Interpreter& interpreter) const
  2105. {
  2106. auto base_value = interpreter.get(m_base);
  2107. interpreter.set(dst(), TRY(Bytecode::delete_by_id(interpreter, base_value, m_property)));
  2108. return {};
  2109. }
  2110. ThrowCompletionOr<void> DeleteByIdWithThis::execute_impl(Bytecode::Interpreter& interpreter) const
  2111. {
  2112. auto& vm = interpreter.vm();
  2113. auto base_value = interpreter.get(m_base);
  2114. auto const& identifier = interpreter.current_executable().get_identifier(m_property);
  2115. bool strict = vm.in_strict_mode();
  2116. auto reference = Reference { base_value, identifier, interpreter.get(m_this_value), strict };
  2117. interpreter.set(dst(), Value(TRY(reference.delete_(vm))));
  2118. return {};
  2119. }
  2120. ThrowCompletionOr<void> ResolveThisBinding::execute_impl(Bytecode::Interpreter& interpreter) const
  2121. {
  2122. auto& cached_this_value = interpreter.reg(Register::this_value());
  2123. if (!cached_this_value.is_empty())
  2124. return {};
  2125. // OPTIMIZATION: Because the value of 'this' cannot be reassigned during a function execution, it's
  2126. // resolved once and then saved for subsequent use.
  2127. auto& running_execution_context = interpreter.running_execution_context();
  2128. if (auto function = running_execution_context.function; function && is<ECMAScriptFunctionObject>(*function) && !static_cast<ECMAScriptFunctionObject&>(*function).allocates_function_environment()) {
  2129. cached_this_value = running_execution_context.this_value;
  2130. } else {
  2131. auto& vm = interpreter.vm();
  2132. cached_this_value = TRY(vm.resolve_this_binding());
  2133. }
  2134. return {};
  2135. }
  2136. // https://tc39.es/ecma262/#sec-makesuperpropertyreference
  2137. ThrowCompletionOr<void> ResolveSuperBase::execute_impl(Bytecode::Interpreter& interpreter) const
  2138. {
  2139. auto& vm = interpreter.vm();
  2140. // 1. Let env be GetThisEnvironment().
  2141. auto& env = verify_cast<FunctionEnvironment>(*get_this_environment(vm));
  2142. // 2. Assert: env.HasSuperBinding() is true.
  2143. VERIFY(env.has_super_binding());
  2144. // 3. Let baseValue be ? env.GetSuperBase().
  2145. interpreter.set(dst(), TRY(env.get_super_base()));
  2146. return {};
  2147. }
  2148. void GetNewTarget::execute_impl(Bytecode::Interpreter& interpreter) const
  2149. {
  2150. interpreter.set(dst(), interpreter.vm().get_new_target());
  2151. }
  2152. void GetImportMeta::execute_impl(Bytecode::Interpreter& interpreter) const
  2153. {
  2154. interpreter.set(dst(), interpreter.vm().get_import_meta());
  2155. }
  2156. static ThrowCompletionOr<Value> dispatch_builtin_call(Bytecode::Interpreter& interpreter, Bytecode::Builtin builtin, ReadonlySpan<Operand> arguments)
  2157. {
  2158. switch (builtin) {
  2159. case Builtin::MathAbs:
  2160. return TRY(MathObject::abs_impl(interpreter.vm(), interpreter.get(arguments[0])));
  2161. case Builtin::MathLog:
  2162. return TRY(MathObject::log_impl(interpreter.vm(), interpreter.get(arguments[0])));
  2163. case Builtin::MathPow:
  2164. return TRY(MathObject::pow_impl(interpreter.vm(), interpreter.get(arguments[0]), interpreter.get(arguments[1])));
  2165. case Builtin::MathExp:
  2166. return TRY(MathObject::exp_impl(interpreter.vm(), interpreter.get(arguments[0])));
  2167. case Builtin::MathCeil:
  2168. return TRY(MathObject::ceil_impl(interpreter.vm(), interpreter.get(arguments[0])));
  2169. case Builtin::MathFloor:
  2170. return TRY(MathObject::floor_impl(interpreter.vm(), interpreter.get(arguments[0])));
  2171. case Builtin::MathRound:
  2172. return TRY(MathObject::round_impl(interpreter.vm(), interpreter.get(arguments[0])));
  2173. case Builtin::MathSqrt:
  2174. return TRY(MathObject::sqrt_impl(interpreter.vm(), interpreter.get(arguments[0])));
  2175. case Bytecode::Builtin::__Count:
  2176. VERIFY_NOT_REACHED();
  2177. }
  2178. VERIFY_NOT_REACHED();
  2179. }
  2180. ThrowCompletionOr<void> Call::execute_impl(Bytecode::Interpreter& interpreter) const
  2181. {
  2182. auto callee = interpreter.get(m_callee);
  2183. TRY(throw_if_needed_for_call(interpreter, callee, call_type(), expression_string()));
  2184. if (m_builtin.has_value()
  2185. && m_argument_count == Bytecode::builtin_argument_count(m_builtin.value())
  2186. && callee.is_object()
  2187. && interpreter.realm().get_builtin_value(m_builtin.value()) == &callee.as_object()) {
  2188. interpreter.set(dst(), TRY(dispatch_builtin_call(interpreter, m_builtin.value(), { m_arguments, m_argument_count })));
  2189. return {};
  2190. }
  2191. Vector<Value> argument_values;
  2192. argument_values.ensure_capacity(m_argument_count);
  2193. for (size_t i = 0; i < m_argument_count; ++i)
  2194. argument_values.unchecked_append(interpreter.get(m_arguments[i]));
  2195. interpreter.set(dst(), TRY(perform_call(interpreter, interpreter.get(m_this_value), call_type(), callee, argument_values)));
  2196. return {};
  2197. }
  2198. ThrowCompletionOr<void> CallWithArgumentArray::execute_impl(Bytecode::Interpreter& interpreter) const
  2199. {
  2200. auto callee = interpreter.get(m_callee);
  2201. TRY(throw_if_needed_for_call(interpreter, callee, call_type(), expression_string()));
  2202. auto argument_values = argument_list_evaluation(interpreter.vm(), interpreter.get(arguments()));
  2203. interpreter.set(dst(), TRY(perform_call(interpreter, interpreter.get(m_this_value), call_type(), callee, move(argument_values))));
  2204. return {};
  2205. }
  2206. // 13.3.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  2207. ThrowCompletionOr<void> SuperCallWithArgumentArray::execute_impl(Bytecode::Interpreter& interpreter) const
  2208. {
  2209. interpreter.set(dst(), TRY(super_call_with_argument_array(interpreter.vm(), interpreter.get(arguments()), m_is_synthetic)));
  2210. return {};
  2211. }
  2212. void NewFunction::execute_impl(Bytecode::Interpreter& interpreter) const
  2213. {
  2214. auto& vm = interpreter.vm();
  2215. interpreter.set(dst(), new_function(vm, m_function_node, m_lhs_name, m_home_object));
  2216. }
  2217. void Return::execute_impl(Bytecode::Interpreter& interpreter) const
  2218. {
  2219. if (m_value.has_value())
  2220. interpreter.do_return(interpreter.get(*m_value));
  2221. else
  2222. interpreter.do_return(js_undefined());
  2223. }
  2224. ThrowCompletionOr<void> Increment::execute_impl(Bytecode::Interpreter& interpreter) const
  2225. {
  2226. auto& vm = interpreter.vm();
  2227. auto old_value = interpreter.get(dst());
  2228. // OPTIMIZATION: Fast path for Int32 values.
  2229. if (old_value.is_int32()) {
  2230. auto integer_value = old_value.as_i32();
  2231. if (integer_value != NumericLimits<i32>::max()) [[likely]] {
  2232. interpreter.set(dst(), Value { integer_value + 1 });
  2233. return {};
  2234. }
  2235. }
  2236. old_value = TRY(old_value.to_numeric(vm));
  2237. if (old_value.is_number())
  2238. interpreter.set(dst(), Value(old_value.as_double() + 1));
  2239. else
  2240. interpreter.set(dst(), BigInt::create(vm, old_value.as_bigint().big_integer().plus(Crypto::SignedBigInteger { 1 })));
  2241. return {};
  2242. }
  2243. ThrowCompletionOr<void> PostfixIncrement::execute_impl(Bytecode::Interpreter& interpreter) const
  2244. {
  2245. auto& vm = interpreter.vm();
  2246. auto old_value = interpreter.get(m_src);
  2247. // OPTIMIZATION: Fast path for Int32 values.
  2248. if (old_value.is_int32()) {
  2249. auto integer_value = old_value.as_i32();
  2250. if (integer_value != NumericLimits<i32>::max()) [[likely]] {
  2251. interpreter.set(m_dst, old_value);
  2252. interpreter.set(m_src, Value { integer_value + 1 });
  2253. return {};
  2254. }
  2255. }
  2256. old_value = TRY(old_value.to_numeric(vm));
  2257. interpreter.set(m_dst, old_value);
  2258. if (old_value.is_number())
  2259. interpreter.set(m_src, Value(old_value.as_double() + 1));
  2260. else
  2261. interpreter.set(m_src, BigInt::create(vm, old_value.as_bigint().big_integer().plus(Crypto::SignedBigInteger { 1 })));
  2262. return {};
  2263. }
  2264. ThrowCompletionOr<void> Decrement::execute_impl(Bytecode::Interpreter& interpreter) const
  2265. {
  2266. auto& vm = interpreter.vm();
  2267. auto old_value = interpreter.get(dst());
  2268. old_value = TRY(old_value.to_numeric(vm));
  2269. if (old_value.is_number())
  2270. interpreter.set(dst(), Value(old_value.as_double() - 1));
  2271. else
  2272. interpreter.set(dst(), BigInt::create(vm, old_value.as_bigint().big_integer().minus(Crypto::SignedBigInteger { 1 })));
  2273. return {};
  2274. }
  2275. ThrowCompletionOr<void> PostfixDecrement::execute_impl(Bytecode::Interpreter& interpreter) const
  2276. {
  2277. auto& vm = interpreter.vm();
  2278. auto old_value = interpreter.get(m_src);
  2279. old_value = TRY(old_value.to_numeric(vm));
  2280. interpreter.set(m_dst, old_value);
  2281. if (old_value.is_number())
  2282. interpreter.set(m_src, Value(old_value.as_double() - 1));
  2283. else
  2284. interpreter.set(m_src, BigInt::create(vm, old_value.as_bigint().big_integer().minus(Crypto::SignedBigInteger { 1 })));
  2285. return {};
  2286. }
  2287. ThrowCompletionOr<void> Throw::execute_impl(Bytecode::Interpreter& interpreter) const
  2288. {
  2289. return throw_completion(interpreter.get(src()));
  2290. }
  2291. ThrowCompletionOr<void> ThrowIfNotObject::execute_impl(Bytecode::Interpreter& interpreter) const
  2292. {
  2293. auto& vm = interpreter.vm();
  2294. auto src = interpreter.get(m_src);
  2295. if (!src.is_object())
  2296. return vm.throw_completion<TypeError>(ErrorType::NotAnObject, src.to_string_without_side_effects());
  2297. return {};
  2298. }
  2299. ThrowCompletionOr<void> ThrowIfNullish::execute_impl(Bytecode::Interpreter& interpreter) const
  2300. {
  2301. auto& vm = interpreter.vm();
  2302. auto value = interpreter.get(m_src);
  2303. if (value.is_nullish())
  2304. return vm.throw_completion<TypeError>(ErrorType::NotObjectCoercible, value.to_string_without_side_effects());
  2305. return {};
  2306. }
  2307. ThrowCompletionOr<void> ThrowIfTDZ::execute_impl(Bytecode::Interpreter& interpreter) const
  2308. {
  2309. auto& vm = interpreter.vm();
  2310. auto value = interpreter.get(m_src);
  2311. if (value.is_empty())
  2312. return vm.throw_completion<ReferenceError>(ErrorType::BindingNotInitialized, value.to_string_without_side_effects());
  2313. return {};
  2314. }
  2315. void LeaveLexicalEnvironment::execute_impl(Bytecode::Interpreter& interpreter) const
  2316. {
  2317. auto& running_execution_context = interpreter.running_execution_context();
  2318. running_execution_context.lexical_environment = running_execution_context.saved_lexical_environments.take_last();
  2319. }
  2320. void LeavePrivateEnvironment::execute_impl(Bytecode::Interpreter& interpreter) const
  2321. {
  2322. auto& running_execution_context = interpreter.vm().running_execution_context();
  2323. running_execution_context.private_environment = running_execution_context.private_environment->outer_environment();
  2324. }
  2325. void LeaveUnwindContext::execute_impl(Bytecode::Interpreter& interpreter) const
  2326. {
  2327. interpreter.leave_unwind_context();
  2328. }
  2329. void Yield::execute_impl(Bytecode::Interpreter& interpreter) const
  2330. {
  2331. auto yielded_value = interpreter.get(m_value).value_or(js_undefined());
  2332. interpreter.do_return(
  2333. interpreter.do_yield(yielded_value, m_continuation_label));
  2334. }
  2335. void PrepareYield::execute_impl(Bytecode::Interpreter& interpreter) const
  2336. {
  2337. auto value = interpreter.get(m_value).value_or(js_undefined());
  2338. interpreter.set(m_dest, interpreter.do_yield(value, {}));
  2339. }
  2340. void Await::execute_impl(Bytecode::Interpreter& interpreter) const
  2341. {
  2342. auto yielded_value = interpreter.get(m_argument).value_or(js_undefined());
  2343. auto object = Object::create(interpreter.realm(), nullptr);
  2344. object->define_direct_property("result", yielded_value, JS::default_attributes);
  2345. // FIXME: If we get a pointer, which is not accurately representable as a double
  2346. // will cause this to explode
  2347. object->define_direct_property("continuation", Value(m_continuation_label.address()), JS::default_attributes);
  2348. object->define_direct_property("isAwait", Value(true), JS::default_attributes);
  2349. interpreter.do_return(object);
  2350. }
  2351. ThrowCompletionOr<void> GetByValue::execute_impl(Bytecode::Interpreter& interpreter) const
  2352. {
  2353. interpreter.set(dst(), TRY(get_by_value(interpreter.vm(), m_base_identifier, interpreter.get(m_base), interpreter.get(m_property), interpreter.current_executable())));
  2354. return {};
  2355. }
  2356. ThrowCompletionOr<void> GetByValueWithThis::execute_impl(Bytecode::Interpreter& interpreter) const
  2357. {
  2358. auto& vm = interpreter.vm();
  2359. auto property_key_value = interpreter.get(m_property);
  2360. auto object = TRY(interpreter.get(m_base).to_object(vm));
  2361. auto property_key = TRY(property_key_value.to_property_key(vm));
  2362. interpreter.set(dst(), TRY(object->internal_get(property_key, interpreter.get(m_this_value))));
  2363. return {};
  2364. }
  2365. ThrowCompletionOr<void> PutByValue::execute_impl(Bytecode::Interpreter& interpreter) const
  2366. {
  2367. auto& vm = interpreter.vm();
  2368. auto value = interpreter.get(m_src);
  2369. auto base_identifier = interpreter.current_executable().get_identifier(m_base_identifier);
  2370. TRY(put_by_value(vm, interpreter.get(m_base), base_identifier, interpreter.get(m_property), value, m_kind));
  2371. return {};
  2372. }
  2373. ThrowCompletionOr<void> PutByValueWithThis::execute_impl(Bytecode::Interpreter& interpreter) const
  2374. {
  2375. auto& vm = interpreter.vm();
  2376. auto value = interpreter.get(m_src);
  2377. auto base = interpreter.get(m_base);
  2378. auto property_key = m_kind != PropertyKind::Spread ? TRY(interpreter.get(m_property).to_property_key(vm)) : PropertyKey {};
  2379. TRY(put_by_property_key(vm, base, interpreter.get(m_this_value), value, {}, property_key, m_kind));
  2380. return {};
  2381. }
  2382. ThrowCompletionOr<void> DeleteByValue::execute_impl(Bytecode::Interpreter& interpreter) const
  2383. {
  2384. auto base_value = interpreter.get(m_base);
  2385. auto property_key_value = interpreter.get(m_property);
  2386. interpreter.set(dst(), TRY(delete_by_value(interpreter, base_value, property_key_value)));
  2387. return {};
  2388. }
  2389. ThrowCompletionOr<void> DeleteByValueWithThis::execute_impl(Bytecode::Interpreter& interpreter) const
  2390. {
  2391. auto property_key_value = interpreter.get(m_property);
  2392. auto base_value = interpreter.get(m_base);
  2393. auto this_value = interpreter.get(m_this_value);
  2394. interpreter.set(dst(), TRY(delete_by_value_with_this(interpreter, base_value, property_key_value, this_value)));
  2395. return {};
  2396. }
  2397. ThrowCompletionOr<void> GetIterator::execute_impl(Bytecode::Interpreter& interpreter) const
  2398. {
  2399. auto& vm = interpreter.vm();
  2400. interpreter.set(dst(), TRY(get_iterator(vm, interpreter.get(iterable()), m_hint)));
  2401. return {};
  2402. }
  2403. ThrowCompletionOr<void> GetObjectFromIteratorRecord::execute_impl(Bytecode::Interpreter& interpreter) const
  2404. {
  2405. auto& iterator_record = verify_cast<IteratorRecord>(interpreter.get(m_iterator_record).as_object());
  2406. interpreter.set(m_object, iterator_record.iterator);
  2407. return {};
  2408. }
  2409. ThrowCompletionOr<void> GetNextMethodFromIteratorRecord::execute_impl(Bytecode::Interpreter& interpreter) const
  2410. {
  2411. auto& iterator_record = verify_cast<IteratorRecord>(interpreter.get(m_iterator_record).as_object());
  2412. interpreter.set(m_next_method, iterator_record.next_method);
  2413. return {};
  2414. }
  2415. ThrowCompletionOr<void> GetMethod::execute_impl(Bytecode::Interpreter& interpreter) const
  2416. {
  2417. auto& vm = interpreter.vm();
  2418. auto identifier = interpreter.current_executable().get_identifier(m_property);
  2419. auto method = TRY(interpreter.get(m_object).get_method(vm, identifier));
  2420. interpreter.set(dst(), method ?: js_undefined());
  2421. return {};
  2422. }
  2423. ThrowCompletionOr<void> GetObjectPropertyIterator::execute_impl(Bytecode::Interpreter& interpreter) const
  2424. {
  2425. interpreter.set(dst(), TRY(get_object_property_iterator(interpreter.vm(), interpreter.get(object()))));
  2426. return {};
  2427. }
  2428. ThrowCompletionOr<void> IteratorClose::execute_impl(Bytecode::Interpreter& interpreter) const
  2429. {
  2430. auto& vm = interpreter.vm();
  2431. auto& iterator = verify_cast<IteratorRecord>(interpreter.get(m_iterator_record).as_object());
  2432. // FIXME: Return the value of the resulting completion. (Note that m_completion_value can be empty!)
  2433. TRY(iterator_close(vm, iterator, Completion { m_completion_type, m_completion_value }));
  2434. return {};
  2435. }
  2436. ThrowCompletionOr<void> AsyncIteratorClose::execute_impl(Bytecode::Interpreter& interpreter) const
  2437. {
  2438. auto& vm = interpreter.vm();
  2439. auto& iterator = verify_cast<IteratorRecord>(interpreter.get(m_iterator_record).as_object());
  2440. // FIXME: Return the value of the resulting completion. (Note that m_completion_value can be empty!)
  2441. TRY(async_iterator_close(vm, iterator, Completion { m_completion_type, m_completion_value }));
  2442. return {};
  2443. }
  2444. ThrowCompletionOr<void> IteratorNext::execute_impl(Bytecode::Interpreter& interpreter) const
  2445. {
  2446. auto& vm = interpreter.vm();
  2447. auto& iterator_record = verify_cast<IteratorRecord>(interpreter.get(m_iterator_record).as_object());
  2448. interpreter.set(dst(), TRY(iterator_next(vm, iterator_record)));
  2449. return {};
  2450. }
  2451. ThrowCompletionOr<void> NewClass::execute_impl(Bytecode::Interpreter& interpreter) const
  2452. {
  2453. Value super_class;
  2454. if (m_super_class.has_value())
  2455. super_class = interpreter.get(m_super_class.value());
  2456. Vector<Value> element_keys;
  2457. for (size_t i = 0; i < m_element_keys_count; ++i) {
  2458. Value element_key;
  2459. if (m_element_keys[i].has_value())
  2460. element_key = interpreter.get(m_element_keys[i].value());
  2461. element_keys.append(element_key);
  2462. }
  2463. interpreter.set(dst(), TRY(new_class(interpreter.vm(), super_class, m_class_expression, m_lhs_name, element_keys)));
  2464. return {};
  2465. }
  2466. // 13.5.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-typeof-operator-runtime-semantics-evaluation
  2467. ThrowCompletionOr<void> TypeofBinding::execute_impl(Bytecode::Interpreter& interpreter) const
  2468. {
  2469. auto& vm = interpreter.vm();
  2470. if (m_cache.is_valid()) {
  2471. auto const* environment = interpreter.running_execution_context().lexical_environment.ptr();
  2472. for (size_t i = 0; i < m_cache.hops; ++i)
  2473. environment = environment->outer_environment();
  2474. if (!environment->is_permanently_screwed_by_eval()) {
  2475. auto value = TRY(static_cast<DeclarativeEnvironment const&>(*environment).get_binding_value_direct(vm, m_cache.index));
  2476. interpreter.set(dst(), value.typeof_(vm));
  2477. return {};
  2478. }
  2479. m_cache = {};
  2480. }
  2481. // 1. Let val be the result of evaluating UnaryExpression.
  2482. auto reference = TRY(vm.resolve_binding(interpreter.current_executable().get_identifier(m_identifier)));
  2483. // 2. If val is a Reference Record, then
  2484. // a. If IsUnresolvableReference(val) is true, return "undefined".
  2485. if (reference.is_unresolvable()) {
  2486. interpreter.set(dst(), PrimitiveString::create(vm, "undefined"_string));
  2487. return {};
  2488. }
  2489. // 3. Set val to ? GetValue(val).
  2490. auto value = TRY(reference.get_value(vm));
  2491. if (reference.environment_coordinate().has_value())
  2492. m_cache = reference.environment_coordinate().value();
  2493. // 4. NOTE: This step is replaced in section B.3.6.3.
  2494. // 5. Return a String according to Table 41.
  2495. interpreter.set(dst(), value.typeof_(vm));
  2496. return {};
  2497. }
  2498. void BlockDeclarationInstantiation::execute_impl(Bytecode::Interpreter& interpreter) const
  2499. {
  2500. auto& vm = interpreter.vm();
  2501. auto old_environment = interpreter.running_execution_context().lexical_environment;
  2502. auto& running_execution_context = interpreter.running_execution_context();
  2503. running_execution_context.saved_lexical_environments.append(old_environment);
  2504. running_execution_context.lexical_environment = new_declarative_environment(*old_environment);
  2505. m_scope_node.block_declaration_instantiation(vm, running_execution_context.lexical_environment);
  2506. }
  2507. ByteString Mov::to_byte_string_impl(Bytecode::Executable const& executable) const
  2508. {
  2509. return ByteString::formatted("Mov {}, {}",
  2510. format_operand("dst"sv, m_dst, executable),
  2511. format_operand("src"sv, m_src, executable));
  2512. }
  2513. ByteString NewArray::to_byte_string_impl(Bytecode::Executable const& executable) const
  2514. {
  2515. StringBuilder builder;
  2516. builder.appendff("NewArray {}", format_operand("dst"sv, dst(), executable));
  2517. if (m_element_count != 0) {
  2518. builder.appendff(", {}", format_operand_list("args"sv, { m_elements, m_element_count }, executable));
  2519. }
  2520. return builder.to_byte_string();
  2521. }
  2522. ByteString NewPrimitiveArray::to_byte_string_impl(Bytecode::Executable const& executable) const
  2523. {
  2524. return ByteString::formatted("NewPrimitiveArray {}, {}"sv,
  2525. format_operand("dst"sv, dst(), executable),
  2526. format_value_list("elements"sv, elements()));
  2527. }
  2528. ByteString AddPrivateName::to_byte_string_impl(Bytecode::Executable const& executable) const
  2529. {
  2530. return ByteString::formatted("AddPrivateName {}"sv, executable.identifier_table->get(m_name));
  2531. }
  2532. ByteString ArrayAppend::to_byte_string_impl(Bytecode::Executable const& executable) const
  2533. {
  2534. return ByteString::formatted("Append {}, {}{}",
  2535. format_operand("dst"sv, dst(), executable),
  2536. format_operand("src"sv, src(), executable),
  2537. m_is_spread ? " **"sv : ""sv);
  2538. }
  2539. ByteString IteratorToArray::to_byte_string_impl(Bytecode::Executable const& executable) const
  2540. {
  2541. return ByteString::formatted("IteratorToArray {}, {}",
  2542. format_operand("dst"sv, dst(), executable),
  2543. format_operand("iterator"sv, iterator(), executable));
  2544. }
  2545. ByteString NewObject::to_byte_string_impl(Bytecode::Executable const& executable) const
  2546. {
  2547. return ByteString::formatted("NewObject {}", format_operand("dst"sv, dst(), executable));
  2548. }
  2549. ByteString NewRegExp::to_byte_string_impl(Bytecode::Executable const& executable) const
  2550. {
  2551. return ByteString::formatted("NewRegExp {}, source:{} (\"{}\") flags:{} (\"{}\")",
  2552. format_operand("dst"sv, dst(), executable),
  2553. m_source_index, executable.get_string(m_source_index), m_flags_index, executable.get_string(m_flags_index));
  2554. }
  2555. ByteString CopyObjectExcludingProperties::to_byte_string_impl(Bytecode::Executable const& executable) const
  2556. {
  2557. StringBuilder builder;
  2558. builder.appendff("CopyObjectExcludingProperties {}, {}",
  2559. format_operand("dst"sv, dst(), executable),
  2560. format_operand("from"sv, m_from_object, executable));
  2561. if (m_excluded_names_count != 0) {
  2562. builder.append(" excluding:["sv);
  2563. for (size_t i = 0; i < m_excluded_names_count; ++i) {
  2564. if (i != 0)
  2565. builder.append(", "sv);
  2566. builder.append(format_operand("#"sv, m_excluded_names[i], executable));
  2567. }
  2568. builder.append(']');
  2569. }
  2570. return builder.to_byte_string();
  2571. }
  2572. ByteString ConcatString::to_byte_string_impl(Bytecode::Executable const& executable) const
  2573. {
  2574. return ByteString::formatted("ConcatString {}, {}",
  2575. format_operand("dst"sv, dst(), executable),
  2576. format_operand("src"sv, src(), executable));
  2577. }
  2578. ByteString GetCalleeAndThisFromEnvironment::to_byte_string_impl(Bytecode::Executable const& executable) const
  2579. {
  2580. return ByteString::formatted("GetCalleeAndThisFromEnvironment {}, {} <- {}",
  2581. format_operand("callee"sv, m_callee, executable),
  2582. format_operand("this"sv, m_this_value, executable),
  2583. executable.identifier_table->get(m_identifier));
  2584. }
  2585. ByteString GetBinding::to_byte_string_impl(Bytecode::Executable const& executable) const
  2586. {
  2587. return ByteString::formatted("GetBinding {}, {}",
  2588. format_operand("dst"sv, dst(), executable),
  2589. executable.identifier_table->get(m_identifier));
  2590. }
  2591. ByteString GetGlobal::to_byte_string_impl(Bytecode::Executable const& executable) const
  2592. {
  2593. return ByteString::formatted("GetGlobal {}, {}", format_operand("dst"sv, dst(), executable),
  2594. executable.identifier_table->get(m_identifier));
  2595. }
  2596. ByteString DeleteVariable::to_byte_string_impl(Bytecode::Executable const& executable) const
  2597. {
  2598. return ByteString::formatted("DeleteVariable {}", executable.identifier_table->get(m_identifier));
  2599. }
  2600. ByteString CreateLexicalEnvironment::to_byte_string_impl(Bytecode::Executable const&) const
  2601. {
  2602. return "CreateLexicalEnvironment"sv;
  2603. }
  2604. ByteString CreatePrivateEnvironment::to_byte_string_impl(Bytecode::Executable const&) const
  2605. {
  2606. return "CreatePrivateEnvironment"sv;
  2607. }
  2608. ByteString CreateVariableEnvironment::to_byte_string_impl(Bytecode::Executable const&) const
  2609. {
  2610. return "CreateVariableEnvironment"sv;
  2611. }
  2612. ByteString CreateVariable::to_byte_string_impl(Bytecode::Executable const& executable) const
  2613. {
  2614. auto mode_string = m_mode == EnvironmentMode::Lexical ? "Lexical" : "Variable";
  2615. return ByteString::formatted("CreateVariable env:{} immutable:{} global:{} {}", mode_string, m_is_immutable, m_is_global, executable.identifier_table->get(m_identifier));
  2616. }
  2617. ByteString CreateRestParams::to_byte_string_impl(Bytecode::Executable const& executable) const
  2618. {
  2619. return ByteString::formatted("CreateRestParams {}, rest_index:{}", format_operand("dst"sv, m_dst, executable), m_rest_index);
  2620. }
  2621. ByteString CreateArguments::to_byte_string_impl(Bytecode::Executable const& executable) const
  2622. {
  2623. StringBuilder builder;
  2624. builder.appendff("CreateArguments");
  2625. if (m_dst.has_value())
  2626. builder.appendff(" {}", format_operand("dst"sv, *m_dst, executable));
  2627. builder.appendff(" {} immutable:{}", m_kind == Kind::Mapped ? "mapped"sv : "unmapped"sv, m_is_immutable);
  2628. return builder.to_byte_string();
  2629. }
  2630. ByteString EnterObjectEnvironment::to_byte_string_impl(Executable const& executable) const
  2631. {
  2632. return ByteString::formatted("EnterObjectEnvironment {}",
  2633. format_operand("object"sv, m_object, executable));
  2634. }
  2635. ByteString InitializeLexicalBinding::to_byte_string_impl(Bytecode::Executable const& executable) const
  2636. {
  2637. return ByteString::formatted("InitializeLexicalBinding {}, {}",
  2638. executable.identifier_table->get(m_identifier),
  2639. format_operand("src"sv, src(), executable));
  2640. }
  2641. ByteString InitializeVariableBinding::to_byte_string_impl(Bytecode::Executable const& executable) const
  2642. {
  2643. return ByteString::formatted("InitializeVariableBinding {}, {}",
  2644. executable.identifier_table->get(m_identifier),
  2645. format_operand("src"sv, src(), executable));
  2646. }
  2647. ByteString SetLexicalBinding::to_byte_string_impl(Bytecode::Executable const& executable) const
  2648. {
  2649. return ByteString::formatted("SetLexicalBinding {}, {}",
  2650. executable.identifier_table->get(m_identifier),
  2651. format_operand("src"sv, src(), executable));
  2652. }
  2653. ByteString SetVariableBinding::to_byte_string_impl(Bytecode::Executable const& executable) const
  2654. {
  2655. return ByteString::formatted("SetVariableBinding {}, {}",
  2656. executable.identifier_table->get(m_identifier),
  2657. format_operand("src"sv, src(), executable));
  2658. }
  2659. ByteString GetArgument::to_byte_string_impl(Bytecode::Executable const& executable) const
  2660. {
  2661. return ByteString::formatted("GetArgument {}, {}", index(), format_operand("dst"sv, dst(), executable));
  2662. }
  2663. ByteString SetArgument::to_byte_string_impl(Bytecode::Executable const& executable) const
  2664. {
  2665. return ByteString::formatted("SetArgument {}, {}", index(), format_operand("src"sv, src(), executable));
  2666. }
  2667. static StringView property_kind_to_string(PropertyKind kind)
  2668. {
  2669. switch (kind) {
  2670. case PropertyKind::Getter:
  2671. return "getter"sv;
  2672. case PropertyKind::Setter:
  2673. return "setter"sv;
  2674. case PropertyKind::KeyValue:
  2675. return "key-value"sv;
  2676. case PropertyKind::DirectKeyValue:
  2677. return "direct-key-value"sv;
  2678. case PropertyKind::Spread:
  2679. return "spread"sv;
  2680. case PropertyKind::ProtoSetter:
  2681. return "proto-setter"sv;
  2682. }
  2683. VERIFY_NOT_REACHED();
  2684. }
  2685. ByteString PutById::to_byte_string_impl(Bytecode::Executable const& executable) const
  2686. {
  2687. auto kind = property_kind_to_string(m_kind);
  2688. return ByteString::formatted("PutById {}, {}, {}, kind:{}",
  2689. format_operand("base"sv, m_base, executable),
  2690. executable.identifier_table->get(m_property),
  2691. format_operand("src"sv, m_src, executable),
  2692. kind);
  2693. }
  2694. ByteString PutByIdWithThis::to_byte_string_impl(Bytecode::Executable const& executable) const
  2695. {
  2696. auto kind = property_kind_to_string(m_kind);
  2697. return ByteString::formatted("PutByIdWithThis {}, {}, {}, {}, kind:{}",
  2698. format_operand("base"sv, m_base, executable),
  2699. executable.identifier_table->get(m_property),
  2700. format_operand("src"sv, m_src, executable),
  2701. format_operand("this"sv, m_this_value, executable),
  2702. kind);
  2703. }
  2704. ByteString PutPrivateById::to_byte_string_impl(Bytecode::Executable const& executable) const
  2705. {
  2706. auto kind = property_kind_to_string(m_kind);
  2707. return ByteString::formatted(
  2708. "PutPrivateById {}, {}, {}, kind:{} ",
  2709. format_operand("base"sv, m_base, executable),
  2710. executable.identifier_table->get(m_property),
  2711. format_operand("src"sv, m_src, executable),
  2712. kind);
  2713. }
  2714. ByteString GetById::to_byte_string_impl(Bytecode::Executable const& executable) const
  2715. {
  2716. return ByteString::formatted("GetById {}, {}, {}",
  2717. format_operand("dst"sv, m_dst, executable),
  2718. format_operand("base"sv, m_base, executable),
  2719. executable.identifier_table->get(m_property));
  2720. }
  2721. ByteString GetByIdWithThis::to_byte_string_impl(Bytecode::Executable const& executable) const
  2722. {
  2723. return ByteString::formatted("GetByIdWithThis {}, {}, {}, {}",
  2724. format_operand("dst"sv, m_dst, executable),
  2725. format_operand("base"sv, m_base, executable),
  2726. executable.identifier_table->get(m_property),
  2727. format_operand("this"sv, m_this_value, executable));
  2728. }
  2729. ByteString GetLength::to_byte_string_impl(Bytecode::Executable const& executable) const
  2730. {
  2731. return ByteString::formatted("GetLength {}, {}",
  2732. format_operand("dst"sv, m_dst, executable),
  2733. format_operand("base"sv, m_base, executable));
  2734. }
  2735. ByteString GetLengthWithThis::to_byte_string_impl(Bytecode::Executable const& executable) const
  2736. {
  2737. return ByteString::formatted("GetLengthWithThis {}, {}, {}",
  2738. format_operand("dst"sv, m_dst, executable),
  2739. format_operand("base"sv, m_base, executable),
  2740. format_operand("this"sv, m_this_value, executable));
  2741. }
  2742. ByteString GetPrivateById::to_byte_string_impl(Bytecode::Executable const& executable) const
  2743. {
  2744. return ByteString::formatted("GetPrivateById {}, {}, {}",
  2745. format_operand("dst"sv, m_dst, executable),
  2746. format_operand("base"sv, m_base, executable),
  2747. executable.identifier_table->get(m_property));
  2748. }
  2749. ByteString HasPrivateId::to_byte_string_impl(Bytecode::Executable const& executable) const
  2750. {
  2751. return ByteString::formatted("HasPrivateId {}, {}, {}",
  2752. format_operand("dst"sv, m_dst, executable),
  2753. format_operand("base"sv, m_base, executable),
  2754. executable.identifier_table->get(m_property));
  2755. }
  2756. ByteString DeleteById::to_byte_string_impl(Bytecode::Executable const& executable) const
  2757. {
  2758. return ByteString::formatted("DeleteById {}, {}, {}",
  2759. format_operand("dst"sv, m_dst, executable),
  2760. format_operand("base"sv, m_base, executable),
  2761. executable.identifier_table->get(m_property));
  2762. }
  2763. ByteString DeleteByIdWithThis::to_byte_string_impl(Bytecode::Executable const& executable) const
  2764. {
  2765. return ByteString::formatted("DeleteByIdWithThis {}, {}, {}, {}",
  2766. format_operand("dst"sv, m_dst, executable),
  2767. format_operand("base"sv, m_base, executable),
  2768. executable.identifier_table->get(m_property),
  2769. format_operand("this"sv, m_this_value, executable));
  2770. }
  2771. ByteString Jump::to_byte_string_impl(Bytecode::Executable const&) const
  2772. {
  2773. return ByteString::formatted("Jump {}", m_target);
  2774. }
  2775. ByteString JumpIf::to_byte_string_impl(Bytecode::Executable const& executable) const
  2776. {
  2777. return ByteString::formatted("JumpIf {}, \033[32mtrue\033[0m:{} \033[32mfalse\033[0m:{}",
  2778. format_operand("condition"sv, m_condition, executable),
  2779. m_true_target,
  2780. m_false_target);
  2781. }
  2782. ByteString JumpTrue::to_byte_string_impl(Bytecode::Executable const& executable) const
  2783. {
  2784. return ByteString::formatted("JumpTrue {}, {}",
  2785. format_operand("condition"sv, m_condition, executable),
  2786. m_target);
  2787. }
  2788. ByteString JumpFalse::to_byte_string_impl(Bytecode::Executable const& executable) const
  2789. {
  2790. return ByteString::formatted("JumpFalse {}, {}",
  2791. format_operand("condition"sv, m_condition, executable),
  2792. m_target);
  2793. }
  2794. ByteString JumpNullish::to_byte_string_impl(Bytecode::Executable const& executable) const
  2795. {
  2796. return ByteString::formatted("JumpNullish {}, null:{} nonnull:{}",
  2797. format_operand("condition"sv, m_condition, executable),
  2798. m_true_target,
  2799. m_false_target);
  2800. }
  2801. #define HANDLE_COMPARISON_OP(op_TitleCase, op_snake_case, numeric_operator) \
  2802. ByteString Jump##op_TitleCase::to_byte_string_impl(Bytecode::Executable const& executable) const \
  2803. { \
  2804. return ByteString::formatted("Jump" #op_TitleCase " {}, {}, true:{}, false:{}", \
  2805. format_operand("lhs"sv, m_lhs, executable), \
  2806. format_operand("rhs"sv, m_rhs, executable), \
  2807. m_true_target, \
  2808. m_false_target); \
  2809. }
  2810. JS_ENUMERATE_COMPARISON_OPS(HANDLE_COMPARISON_OP)
  2811. ByteString JumpUndefined::to_byte_string_impl(Bytecode::Executable const& executable) const
  2812. {
  2813. return ByteString::formatted("JumpUndefined {}, undefined:{} defined:{}",
  2814. format_operand("condition"sv, m_condition, executable),
  2815. m_true_target,
  2816. m_false_target);
  2817. }
  2818. static StringView call_type_to_string(CallType type)
  2819. {
  2820. switch (type) {
  2821. case CallType::Call:
  2822. return ""sv;
  2823. case CallType::Construct:
  2824. return " (Construct)"sv;
  2825. case CallType::DirectEval:
  2826. return " (DirectEval)"sv;
  2827. }
  2828. VERIFY_NOT_REACHED();
  2829. }
  2830. ByteString Call::to_byte_string_impl(Bytecode::Executable const& executable) const
  2831. {
  2832. auto type = call_type_to_string(m_type);
  2833. StringBuilder builder;
  2834. builder.appendff("Call{} {}, {}, {}, "sv,
  2835. type,
  2836. format_operand("dst"sv, m_dst, executable),
  2837. format_operand("callee"sv, m_callee, executable),
  2838. format_operand("this"sv, m_this_value, executable));
  2839. builder.append(format_operand_list("args"sv, { m_arguments, m_argument_count }, executable));
  2840. if (m_builtin.has_value()) {
  2841. builder.appendff(", (builtin:{})", m_builtin.value());
  2842. }
  2843. if (m_expression_string.has_value()) {
  2844. builder.appendff(", `{}`", executable.get_string(m_expression_string.value()));
  2845. }
  2846. return builder.to_byte_string();
  2847. }
  2848. ByteString CallWithArgumentArray::to_byte_string_impl(Bytecode::Executable const& executable) const
  2849. {
  2850. auto type = call_type_to_string(m_type);
  2851. StringBuilder builder;
  2852. builder.appendff("CallWithArgumentArray{} {}, {}, {}, {}",
  2853. type,
  2854. format_operand("dst"sv, m_dst, executable),
  2855. format_operand("callee"sv, m_callee, executable),
  2856. format_operand("this"sv, m_this_value, executable),
  2857. format_operand("arguments"sv, m_arguments, executable));
  2858. if (m_expression_string.has_value())
  2859. builder.appendff(" ({})", executable.get_string(m_expression_string.value()));
  2860. return builder.to_byte_string();
  2861. }
  2862. ByteString SuperCallWithArgumentArray::to_byte_string_impl(Bytecode::Executable const& executable) const
  2863. {
  2864. return ByteString::formatted("SuperCallWithArgumentArray {}, {}",
  2865. format_operand("dst"sv, m_dst, executable),
  2866. format_operand("arguments"sv, m_arguments, executable));
  2867. }
  2868. ByteString NewFunction::to_byte_string_impl(Bytecode::Executable const& executable) const
  2869. {
  2870. StringBuilder builder;
  2871. builder.appendff("NewFunction {}",
  2872. format_operand("dst"sv, m_dst, executable));
  2873. if (m_function_node.has_name())
  2874. builder.appendff(" name:{}"sv, m_function_node.name());
  2875. if (m_lhs_name.has_value())
  2876. builder.appendff(" lhs_name:{}"sv, executable.get_identifier(m_lhs_name.value()));
  2877. if (m_home_object.has_value())
  2878. builder.appendff(", {}"sv, format_operand("home_object"sv, m_home_object.value(), executable));
  2879. return builder.to_byte_string();
  2880. }
  2881. ByteString NewClass::to_byte_string_impl(Bytecode::Executable const& executable) const
  2882. {
  2883. StringBuilder builder;
  2884. auto name = m_class_expression.name();
  2885. builder.appendff("NewClass {}",
  2886. format_operand("dst"sv, m_dst, executable));
  2887. if (m_super_class.has_value())
  2888. builder.appendff(", {}", format_operand("super_class"sv, *m_super_class, executable));
  2889. if (!name.is_empty())
  2890. builder.appendff(", {}", name);
  2891. if (m_lhs_name.has_value())
  2892. builder.appendff(", lhs_name:{}"sv, executable.get_identifier(m_lhs_name.value()));
  2893. return builder.to_byte_string();
  2894. }
  2895. ByteString Return::to_byte_string_impl(Bytecode::Executable const& executable) const
  2896. {
  2897. if (m_value.has_value())
  2898. return ByteString::formatted("Return {}", format_operand("value"sv, m_value.value(), executable));
  2899. return "Return";
  2900. }
  2901. ByteString Increment::to_byte_string_impl(Bytecode::Executable const& executable) const
  2902. {
  2903. return ByteString::formatted("Increment {}", format_operand("dst"sv, m_dst, executable));
  2904. }
  2905. ByteString PostfixIncrement::to_byte_string_impl(Bytecode::Executable const& executable) const
  2906. {
  2907. return ByteString::formatted("PostfixIncrement {}, {}",
  2908. format_operand("dst"sv, m_dst, executable),
  2909. format_operand("src"sv, m_src, executable));
  2910. }
  2911. ByteString Decrement::to_byte_string_impl(Bytecode::Executable const& executable) const
  2912. {
  2913. return ByteString::formatted("Decrement {}", format_operand("dst"sv, m_dst, executable));
  2914. }
  2915. ByteString PostfixDecrement::to_byte_string_impl(Bytecode::Executable const& executable) const
  2916. {
  2917. return ByteString::formatted("PostfixDecrement {}, {}",
  2918. format_operand("dst"sv, m_dst, executable),
  2919. format_operand("src"sv, m_src, executable));
  2920. }
  2921. ByteString Throw::to_byte_string_impl(Bytecode::Executable const& executable) const
  2922. {
  2923. return ByteString::formatted("Throw {}",
  2924. format_operand("src"sv, m_src, executable));
  2925. }
  2926. ByteString ThrowIfNotObject::to_byte_string_impl(Bytecode::Executable const& executable) const
  2927. {
  2928. return ByteString::formatted("ThrowIfNotObject {}",
  2929. format_operand("src"sv, m_src, executable));
  2930. }
  2931. ByteString ThrowIfNullish::to_byte_string_impl(Bytecode::Executable const& executable) const
  2932. {
  2933. return ByteString::formatted("ThrowIfNullish {}",
  2934. format_operand("src"sv, m_src, executable));
  2935. }
  2936. ByteString ThrowIfTDZ::to_byte_string_impl(Bytecode::Executable const& executable) const
  2937. {
  2938. return ByteString::formatted("ThrowIfTDZ {}",
  2939. format_operand("src"sv, m_src, executable));
  2940. }
  2941. ByteString EnterUnwindContext::to_byte_string_impl(Bytecode::Executable const&) const
  2942. {
  2943. return ByteString::formatted("EnterUnwindContext entry:{}", m_entry_point);
  2944. }
  2945. ByteString ScheduleJump::to_byte_string_impl(Bytecode::Executable const&) const
  2946. {
  2947. return ByteString::formatted("ScheduleJump {}", m_target);
  2948. }
  2949. ByteString LeaveLexicalEnvironment::to_byte_string_impl(Bytecode::Executable const&) const
  2950. {
  2951. return "LeaveLexicalEnvironment"sv;
  2952. }
  2953. ByteString LeavePrivateEnvironment::to_byte_string_impl(Bytecode::Executable const&) const
  2954. {
  2955. return "LeavePrivateEnvironment"sv;
  2956. }
  2957. ByteString LeaveUnwindContext::to_byte_string_impl(Bytecode::Executable const&) const
  2958. {
  2959. return "LeaveUnwindContext";
  2960. }
  2961. ByteString ContinuePendingUnwind::to_byte_string_impl(Bytecode::Executable const&) const
  2962. {
  2963. return ByteString::formatted("ContinuePendingUnwind resume:{}", m_resume_target);
  2964. }
  2965. ByteString Yield::to_byte_string_impl(Bytecode::Executable const& executable) const
  2966. {
  2967. if (m_continuation_label.has_value()) {
  2968. return ByteString::formatted("Yield continuation:{}, {}",
  2969. m_continuation_label.value(),
  2970. format_operand("value"sv, m_value, executable));
  2971. }
  2972. return ByteString::formatted("Yield return {}",
  2973. format_operand("value"sv, m_value, executable));
  2974. }
  2975. ByteString PrepareYield::to_byte_string_impl(Bytecode::Executable const& executable) const
  2976. {
  2977. return ByteString::formatted("PrepareYield {}, {}",
  2978. format_operand("dst"sv, m_dest, executable),
  2979. format_operand("value"sv, m_value, executable));
  2980. }
  2981. ByteString Await::to_byte_string_impl(Bytecode::Executable const& executable) const
  2982. {
  2983. return ByteString::formatted("Await {}, continuation:{}",
  2984. format_operand("argument"sv, m_argument, executable),
  2985. m_continuation_label);
  2986. }
  2987. ByteString GetByValue::to_byte_string_impl(Bytecode::Executable const& executable) const
  2988. {
  2989. return ByteString::formatted("GetByValue {}, {}, {}",
  2990. format_operand("dst"sv, m_dst, executable),
  2991. format_operand("base"sv, m_base, executable),
  2992. format_operand("property"sv, m_property, executable));
  2993. }
  2994. ByteString GetByValueWithThis::to_byte_string_impl(Bytecode::Executable const& executable) const
  2995. {
  2996. return ByteString::formatted("GetByValueWithThis {}, {}, {}",
  2997. format_operand("dst"sv, m_dst, executable),
  2998. format_operand("base"sv, m_base, executable),
  2999. format_operand("property"sv, m_property, executable));
  3000. }
  3001. ByteString PutByValue::to_byte_string_impl(Bytecode::Executable const& executable) const
  3002. {
  3003. auto kind = property_kind_to_string(m_kind);
  3004. return ByteString::formatted("PutByValue {}, {}, {}, kind:{}",
  3005. format_operand("base"sv, m_base, executable),
  3006. format_operand("property"sv, m_property, executable),
  3007. format_operand("src"sv, m_src, executable),
  3008. kind);
  3009. }
  3010. ByteString PutByValueWithThis::to_byte_string_impl(Bytecode::Executable const& executable) const
  3011. {
  3012. auto kind = property_kind_to_string(m_kind);
  3013. return ByteString::formatted("PutByValueWithThis {}, {}, {}, {}, kind:{}",
  3014. format_operand("base"sv, m_base, executable),
  3015. format_operand("property"sv, m_property, executable),
  3016. format_operand("src"sv, m_src, executable),
  3017. format_operand("this"sv, m_this_value, executable),
  3018. kind);
  3019. }
  3020. ByteString DeleteByValue::to_byte_string_impl(Bytecode::Executable const& executable) const
  3021. {
  3022. return ByteString::formatted("DeleteByValue {}, {}, {}",
  3023. format_operand("dst"sv, dst(), executable),
  3024. format_operand("base"sv, m_base, executable),
  3025. format_operand("property"sv, m_property, executable));
  3026. }
  3027. ByteString DeleteByValueWithThis::to_byte_string_impl(Bytecode::Executable const& executable) const
  3028. {
  3029. return ByteString::formatted("DeleteByValueWithThis {}, {}, {}, {}",
  3030. format_operand("dst"sv, dst(), executable),
  3031. format_operand("base"sv, m_base, executable),
  3032. format_operand("property"sv, m_property, executable),
  3033. format_operand("this"sv, m_this_value, executable));
  3034. }
  3035. ByteString GetIterator::to_byte_string_impl(Executable const& executable) const
  3036. {
  3037. auto hint = m_hint == IteratorHint::Sync ? "sync" : "async";
  3038. return ByteString::formatted("GetIterator {}, {}, hint:{}",
  3039. format_operand("dst"sv, m_dst, executable),
  3040. format_operand("iterable"sv, m_iterable, executable),
  3041. hint);
  3042. }
  3043. ByteString GetMethod::to_byte_string_impl(Bytecode::Executable const& executable) const
  3044. {
  3045. return ByteString::formatted("GetMethod {}, {}, {}",
  3046. format_operand("dst"sv, m_dst, executable),
  3047. format_operand("object"sv, m_object, executable),
  3048. executable.identifier_table->get(m_property));
  3049. }
  3050. ByteString GetObjectPropertyIterator::to_byte_string_impl(Bytecode::Executable const& executable) const
  3051. {
  3052. return ByteString::formatted("GetObjectPropertyIterator {}, {}",
  3053. format_operand("dst"sv, dst(), executable),
  3054. format_operand("object"sv, object(), executable));
  3055. }
  3056. ByteString IteratorClose::to_byte_string_impl(Bytecode::Executable const& executable) const
  3057. {
  3058. if (!m_completion_value.has_value())
  3059. return ByteString::formatted("IteratorClose {}, completion_type={} completion_value=<empty>",
  3060. format_operand("iterator_record"sv, m_iterator_record, executable),
  3061. to_underlying(m_completion_type));
  3062. auto completion_value_string = m_completion_value->to_string_without_side_effects();
  3063. return ByteString::formatted("IteratorClose {}, completion_type={} completion_value={}",
  3064. format_operand("iterator_record"sv, m_iterator_record, executable),
  3065. to_underlying(m_completion_type), completion_value_string);
  3066. }
  3067. ByteString AsyncIteratorClose::to_byte_string_impl(Bytecode::Executable const& executable) const
  3068. {
  3069. if (!m_completion_value.has_value()) {
  3070. return ByteString::formatted("AsyncIteratorClose {}, completion_type:{} completion_value:<empty>",
  3071. format_operand("iterator_record"sv, m_iterator_record, executable),
  3072. to_underlying(m_completion_type));
  3073. }
  3074. return ByteString::formatted("AsyncIteratorClose {}, completion_type:{}, completion_value:{}",
  3075. format_operand("iterator_record"sv, m_iterator_record, executable),
  3076. to_underlying(m_completion_type), m_completion_value);
  3077. }
  3078. ByteString IteratorNext::to_byte_string_impl(Executable const& executable) const
  3079. {
  3080. return ByteString::formatted("IteratorNext {}, {}",
  3081. format_operand("dst"sv, m_dst, executable),
  3082. format_operand("iterator_record"sv, m_iterator_record, executable));
  3083. }
  3084. ByteString ResolveThisBinding::to_byte_string_impl(Bytecode::Executable const&) const
  3085. {
  3086. return "ResolveThisBinding"sv;
  3087. }
  3088. ByteString ResolveSuperBase::to_byte_string_impl(Bytecode::Executable const& executable) const
  3089. {
  3090. return ByteString::formatted("ResolveSuperBase {}",
  3091. format_operand("dst"sv, m_dst, executable));
  3092. }
  3093. ByteString GetNewTarget::to_byte_string_impl(Bytecode::Executable const& executable) const
  3094. {
  3095. return ByteString::formatted("GetNewTarget {}", format_operand("dst"sv, m_dst, executable));
  3096. }
  3097. ByteString GetImportMeta::to_byte_string_impl(Bytecode::Executable const& executable) const
  3098. {
  3099. return ByteString::formatted("GetImportMeta {}", format_operand("dst"sv, m_dst, executable));
  3100. }
  3101. ByteString TypeofBinding::to_byte_string_impl(Bytecode::Executable const& executable) const
  3102. {
  3103. return ByteString::formatted("TypeofBinding {}, {}",
  3104. format_operand("dst"sv, m_dst, executable),
  3105. executable.identifier_table->get(m_identifier));
  3106. }
  3107. ByteString BlockDeclarationInstantiation::to_byte_string_impl(Bytecode::Executable const&) const
  3108. {
  3109. return "BlockDeclarationInstantiation"sv;
  3110. }
  3111. ByteString ImportCall::to_byte_string_impl(Bytecode::Executable const& executable) const
  3112. {
  3113. return ByteString::formatted("ImportCall {}, {}, {}",
  3114. format_operand("dst"sv, m_dst, executable),
  3115. format_operand("specifier"sv, m_specifier, executable),
  3116. format_operand("options"sv, m_options, executable));
  3117. }
  3118. ByteString Catch::to_byte_string_impl(Bytecode::Executable const& executable) const
  3119. {
  3120. return ByteString::formatted("Catch {}",
  3121. format_operand("dst"sv, m_dst, executable));
  3122. }
  3123. ByteString LeaveFinally::to_byte_string_impl(Bytecode::Executable const&) const
  3124. {
  3125. return ByteString::formatted("LeaveFinally");
  3126. }
  3127. ByteString RestoreScheduledJump::to_byte_string_impl(Bytecode::Executable const&) const
  3128. {
  3129. return ByteString::formatted("RestoreScheduledJump");
  3130. }
  3131. ByteString GetObjectFromIteratorRecord::to_byte_string_impl(Bytecode::Executable const& executable) const
  3132. {
  3133. return ByteString::formatted("GetObjectFromIteratorRecord {}, {}",
  3134. format_operand("object"sv, m_object, executable),
  3135. format_operand("iterator_record"sv, m_iterator_record, executable));
  3136. }
  3137. ByteString GetNextMethodFromIteratorRecord::to_byte_string_impl(Bytecode::Executable const& executable) const
  3138. {
  3139. return ByteString::formatted("GetNextMethodFromIteratorRecord {}, {}",
  3140. format_operand("next_method"sv, m_next_method, executable),
  3141. format_operand("iterator_record"sv, m_iterator_record, executable));
  3142. }
  3143. ByteString End::to_byte_string_impl(Bytecode::Executable const& executable) const
  3144. {
  3145. return ByteString::formatted("End {}", format_operand("value"sv, m_value, executable));
  3146. }
  3147. ByteString Dump::to_byte_string_impl(Bytecode::Executable const& executable) const
  3148. {
  3149. return ByteString::formatted("Dump '{}', {}", m_text,
  3150. format_operand("value"sv, m_value, executable));
  3151. }
  3152. }