Interpreter.cpp 164 KB

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