Interpreter.cpp 158 KB

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