Interpreter.cpp 158 KB

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