Interpreter.cpp 162 KB

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