js.cpp 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Assertions.h>
  8. #include <AK/ByteBuffer.h>
  9. #include <AK/Format.h>
  10. #include <AK/NonnullOwnPtr.h>
  11. #include <AK/StringBuilder.h>
  12. #include <LibCore/ArgsParser.h>
  13. #include <LibCore/ConfigFile.h>
  14. #include <LibCore/File.h>
  15. #include <LibCore/StandardPaths.h>
  16. #include <LibCore/System.h>
  17. #include <LibJS/AST.h>
  18. #include <LibJS/Bytecode/BasicBlock.h>
  19. #include <LibJS/Bytecode/Generator.h>
  20. #include <LibJS/Bytecode/Interpreter.h>
  21. #include <LibJS/Bytecode/PassManager.h>
  22. #include <LibJS/Console.h>
  23. #include <LibJS/Interpreter.h>
  24. #include <LibJS/Parser.h>
  25. #include <LibJS/Runtime/Array.h>
  26. #include <LibJS/Runtime/ArrayBuffer.h>
  27. #include <LibJS/Runtime/AsyncGenerator.h>
  28. #include <LibJS/Runtime/BooleanObject.h>
  29. #include <LibJS/Runtime/DataView.h>
  30. #include <LibJS/Runtime/Date.h>
  31. #include <LibJS/Runtime/DatePrototype.h>
  32. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  33. #include <LibJS/Runtime/Error.h>
  34. #include <LibJS/Runtime/FunctionObject.h>
  35. #include <LibJS/Runtime/GeneratorObject.h>
  36. #include <LibJS/Runtime/GlobalObject.h>
  37. #include <LibJS/Runtime/Intl/Collator.h>
  38. #include <LibJS/Runtime/Intl/DateTimeFormat.h>
  39. #include <LibJS/Runtime/Intl/DisplayNames.h>
  40. #include <LibJS/Runtime/Intl/DurationFormat.h>
  41. #include <LibJS/Runtime/Intl/ListFormat.h>
  42. #include <LibJS/Runtime/Intl/Locale.h>
  43. #include <LibJS/Runtime/Intl/NumberFormat.h>
  44. #include <LibJS/Runtime/Intl/PluralRules.h>
  45. #include <LibJS/Runtime/Intl/RelativeTimeFormat.h>
  46. #include <LibJS/Runtime/Intl/Segmenter.h>
  47. #include <LibJS/Runtime/Intl/Segments.h>
  48. #include <LibJS/Runtime/JSONObject.h>
  49. #include <LibJS/Runtime/Map.h>
  50. #include <LibJS/Runtime/NativeFunction.h>
  51. #include <LibJS/Runtime/NumberObject.h>
  52. #include <LibJS/Runtime/Object.h>
  53. #include <LibJS/Runtime/PrimitiveString.h>
  54. #include <LibJS/Runtime/Promise.h>
  55. #include <LibJS/Runtime/ProxyObject.h>
  56. #include <LibJS/Runtime/RegExpObject.h>
  57. #include <LibJS/Runtime/Set.h>
  58. #include <LibJS/Runtime/ShadowRealm.h>
  59. #include <LibJS/Runtime/Shape.h>
  60. #include <LibJS/Runtime/StringObject.h>
  61. #include <LibJS/Runtime/StringPrototype.h>
  62. #include <LibJS/Runtime/Temporal/Calendar.h>
  63. #include <LibJS/Runtime/Temporal/Duration.h>
  64. #include <LibJS/Runtime/Temporal/Instant.h>
  65. #include <LibJS/Runtime/Temporal/PlainDate.h>
  66. #include <LibJS/Runtime/Temporal/PlainDateTime.h>
  67. #include <LibJS/Runtime/Temporal/PlainMonthDay.h>
  68. #include <LibJS/Runtime/Temporal/PlainTime.h>
  69. #include <LibJS/Runtime/Temporal/PlainYearMonth.h>
  70. #include <LibJS/Runtime/Temporal/TimeZone.h>
  71. #include <LibJS/Runtime/Temporal/ZonedDateTime.h>
  72. #include <LibJS/Runtime/TypedArray.h>
  73. #include <LibJS/Runtime/Value.h>
  74. #include <LibJS/Runtime/WeakMap.h>
  75. #include <LibJS/Runtime/WeakRef.h>
  76. #include <LibJS/Runtime/WeakSet.h>
  77. #include <LibJS/SourceTextModule.h>
  78. #include <LibLine/Editor.h>
  79. #include <LibMain/Main.h>
  80. #include <LibTextCodec/Decoder.h>
  81. #include <fcntl.h>
  82. #include <signal.h>
  83. #include <stdio.h>
  84. #include <unistd.h>
  85. RefPtr<JS::VM> g_vm;
  86. Vector<String> g_repl_statements;
  87. JS::Handle<JS::Value> g_last_value = JS::make_handle(JS::js_undefined());
  88. class ReplObject final : public JS::GlobalObject {
  89. JS_OBJECT(ReplObject, JS::GlobalObject);
  90. public:
  91. ReplObject() = default;
  92. virtual void initialize_global_object() override;
  93. virtual ~ReplObject() override = default;
  94. private:
  95. JS_DECLARE_NATIVE_FUNCTION(exit_interpreter);
  96. JS_DECLARE_NATIVE_FUNCTION(repl_help);
  97. JS_DECLARE_NATIVE_FUNCTION(save_to_file);
  98. JS_DECLARE_NATIVE_FUNCTION(load_ini);
  99. JS_DECLARE_NATIVE_FUNCTION(load_json);
  100. JS_DECLARE_NATIVE_FUNCTION(last_value_getter);
  101. JS_DECLARE_NATIVE_FUNCTION(print);
  102. };
  103. class ScriptObject final : public JS::GlobalObject {
  104. JS_OBJECT(ScriptObject, JS::GlobalObject);
  105. public:
  106. ScriptObject() = default;
  107. virtual void initialize_global_object() override;
  108. virtual ~ScriptObject() override = default;
  109. private:
  110. JS_DECLARE_NATIVE_FUNCTION(load_ini);
  111. JS_DECLARE_NATIVE_FUNCTION(load_json);
  112. JS_DECLARE_NATIVE_FUNCTION(print);
  113. };
  114. static bool s_dump_ast = false;
  115. static bool s_run_bytecode = false;
  116. static bool s_opt_bytecode = false;
  117. static bool s_as_module = false;
  118. static bool s_print_last_result = false;
  119. static bool s_strip_ansi = false;
  120. static bool s_disable_source_location_hints = false;
  121. static RefPtr<Line::Editor> s_editor;
  122. static String s_history_path = String::formatted("{}/.js-history", Core::StandardPaths::home_directory());
  123. static int s_repl_line_level = 0;
  124. static bool s_fail_repl = false;
  125. static String prompt_for_level(int level)
  126. {
  127. static StringBuilder prompt_builder;
  128. prompt_builder.clear();
  129. prompt_builder.append("> "sv);
  130. for (auto i = 0; i < level; ++i)
  131. prompt_builder.append(" "sv);
  132. return prompt_builder.build();
  133. }
  134. static String read_next_piece()
  135. {
  136. StringBuilder piece;
  137. auto line_level_delta_for_next_line { 0 };
  138. do {
  139. auto line_result = s_editor->get_line(prompt_for_level(s_repl_line_level));
  140. line_level_delta_for_next_line = 0;
  141. if (line_result.is_error()) {
  142. s_fail_repl = true;
  143. return "";
  144. }
  145. auto& line = line_result.value();
  146. s_editor->add_to_history(line);
  147. piece.append(line);
  148. piece.append('\n');
  149. auto lexer = JS::Lexer(line);
  150. enum {
  151. NotInLabelOrObjectKey,
  152. InLabelOrObjectKeyIdentifier,
  153. InLabelOrObjectKey
  154. } label_state { NotInLabelOrObjectKey };
  155. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  156. switch (token.type()) {
  157. case JS::TokenType::BracketOpen:
  158. case JS::TokenType::CurlyOpen:
  159. case JS::TokenType::ParenOpen:
  160. label_state = NotInLabelOrObjectKey;
  161. s_repl_line_level++;
  162. break;
  163. case JS::TokenType::BracketClose:
  164. case JS::TokenType::CurlyClose:
  165. case JS::TokenType::ParenClose:
  166. label_state = NotInLabelOrObjectKey;
  167. s_repl_line_level--;
  168. break;
  169. case JS::TokenType::Identifier:
  170. case JS::TokenType::StringLiteral:
  171. if (label_state == NotInLabelOrObjectKey)
  172. label_state = InLabelOrObjectKeyIdentifier;
  173. else
  174. label_state = NotInLabelOrObjectKey;
  175. break;
  176. case JS::TokenType::Colon:
  177. if (label_state == InLabelOrObjectKeyIdentifier)
  178. label_state = InLabelOrObjectKey;
  179. else
  180. label_state = NotInLabelOrObjectKey;
  181. break;
  182. default:
  183. break;
  184. }
  185. }
  186. if (label_state == InLabelOrObjectKey) {
  187. // If there's a label or object literal key at the end of this line,
  188. // prompt for more lines but do not change the line level.
  189. line_level_delta_for_next_line += 1;
  190. }
  191. } while (s_repl_line_level + line_level_delta_for_next_line > 0);
  192. return piece.to_string();
  193. }
  194. static String strip_ansi(StringView format_string)
  195. {
  196. if (format_string.is_empty())
  197. return String::empty();
  198. StringBuilder builder;
  199. size_t i;
  200. for (i = 0; i < format_string.length() - 1; ++i) {
  201. if (format_string[i] == '\033' && format_string[i + 1] == '[') {
  202. while (i < format_string.length() && format_string[i] != 'm')
  203. ++i;
  204. } else {
  205. builder.append(format_string[i]);
  206. }
  207. }
  208. if (i < format_string.length())
  209. builder.append(format_string[i]);
  210. return builder.to_string();
  211. }
  212. template<typename... Parameters>
  213. static void js_out(CheckedFormatString<Parameters...>&& fmtstr, Parameters const&... parameters)
  214. {
  215. if (!s_strip_ansi)
  216. return out(move(fmtstr), parameters...);
  217. auto stripped_fmtstr = strip_ansi(fmtstr.view());
  218. out(stripped_fmtstr, parameters...);
  219. }
  220. template<typename... Parameters>
  221. static void js_outln(CheckedFormatString<Parameters...>&& fmtstr, Parameters const&... parameters)
  222. {
  223. if (!s_strip_ansi)
  224. return outln(move(fmtstr), parameters...);
  225. auto stripped_fmtstr = strip_ansi(fmtstr.view());
  226. outln(stripped_fmtstr, parameters...);
  227. }
  228. inline void js_outln() { outln(); }
  229. static void print_value(JS::Value value, HashTable<JS::Object*>& seen_objects);
  230. static void print_type(FlyString const& name)
  231. {
  232. js_out("[\033[36;1m{}\033[0m]", name);
  233. }
  234. static void print_separator(bool& first)
  235. {
  236. js_out(first ? " "sv : ", "sv);
  237. first = false;
  238. }
  239. static void print_array(JS::Array const& array, HashTable<JS::Object*>& seen_objects)
  240. {
  241. js_out("[");
  242. bool first = true;
  243. for (auto it = array.indexed_properties().begin(false); it != array.indexed_properties().end(); ++it) {
  244. print_separator(first);
  245. auto value_or_error = array.get(it.index());
  246. // The V8 repl doesn't throw an exception here, and instead just
  247. // prints 'undefined'. We may choose to replicate that behavior in
  248. // the future, but for now lets just catch the error
  249. if (value_or_error.is_error())
  250. return;
  251. auto value = value_or_error.release_value();
  252. print_value(value, seen_objects);
  253. }
  254. if (!first)
  255. js_out(" ");
  256. js_out("]");
  257. }
  258. static void print_object(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  259. {
  260. js_out("{{");
  261. bool first = true;
  262. for (auto& entry : object.indexed_properties()) {
  263. print_separator(first);
  264. js_out("\"\033[33;1m{}\033[0m\": ", entry.index());
  265. auto value_or_error = object.get(entry.index());
  266. // The V8 repl doesn't throw an exception here, and instead just
  267. // prints 'undefined'. We may choose to replicate that behavior in
  268. // the future, but for now lets just catch the error
  269. if (value_or_error.is_error())
  270. return;
  271. auto value = value_or_error.release_value();
  272. print_value(value, seen_objects);
  273. }
  274. for (auto& it : object.shape().property_table_ordered()) {
  275. print_separator(first);
  276. if (it.key.is_string()) {
  277. js_out("\"\033[33;1m{}\033[0m\": ", it.key.to_display_string());
  278. } else {
  279. js_out("[\033[33;1m{}\033[0m]: ", it.key.to_display_string());
  280. }
  281. print_value(object.get_direct(it.value.offset), seen_objects);
  282. }
  283. if (!first)
  284. js_out(" ");
  285. js_out("}}");
  286. }
  287. static void print_function(JS::FunctionObject const& function_object, HashTable<JS::Object*>&)
  288. {
  289. if (is<JS::ECMAScriptFunctionObject>(function_object)) {
  290. auto const& ecmascript_function_object = static_cast<JS::ECMAScriptFunctionObject const&>(function_object);
  291. switch (ecmascript_function_object.kind()) {
  292. case JS::FunctionKind::Normal:
  293. print_type("Function");
  294. break;
  295. case JS::FunctionKind::Generator:
  296. print_type("GeneratorFunction");
  297. break;
  298. case JS::FunctionKind::Async:
  299. print_type("AsyncFunction");
  300. break;
  301. case JS::FunctionKind::AsyncGenerator:
  302. print_type("AsyncGeneratorFunction");
  303. break;
  304. default:
  305. VERIFY_NOT_REACHED();
  306. }
  307. } else {
  308. print_type(function_object.class_name());
  309. }
  310. if (is<JS::ECMAScriptFunctionObject>(function_object))
  311. js_out(" {}", static_cast<JS::ECMAScriptFunctionObject const&>(function_object).name());
  312. else if (is<JS::NativeFunction>(function_object))
  313. js_out(" {}", static_cast<JS::NativeFunction const&>(function_object).name());
  314. }
  315. static void print_date(JS::Date const& date, HashTable<JS::Object*>&)
  316. {
  317. print_type("Date");
  318. js_out(" \033[34;1m{}\033[0m", JS::to_date_string(date.date_value()));
  319. }
  320. static void print_error(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  321. {
  322. auto name = object.get_without_side_effects(g_vm->names.name).value_or(JS::js_undefined());
  323. auto message = object.get_without_side_effects(g_vm->names.message).value_or(JS::js_undefined());
  324. if (name.is_accessor() || message.is_accessor()) {
  325. print_value(&object, seen_objects);
  326. } else {
  327. auto name_string = name.to_string_without_side_effects();
  328. auto message_string = message.to_string_without_side_effects();
  329. print_type(name_string);
  330. if (!message_string.is_empty())
  331. js_out(" \033[31;1m{}\033[0m", message_string);
  332. }
  333. }
  334. static void print_regexp_object(JS::RegExpObject const& regexp_object, HashTable<JS::Object*>&)
  335. {
  336. print_type("RegExp");
  337. js_out(" \033[34;1m/{}/{}\033[0m", regexp_object.escape_regexp_pattern(), regexp_object.flags());
  338. }
  339. static void print_proxy_object(JS::ProxyObject const& proxy_object, HashTable<JS::Object*>& seen_objects)
  340. {
  341. print_type("Proxy");
  342. js_out("\n target: ");
  343. print_value(&proxy_object.target(), seen_objects);
  344. js_out("\n handler: ");
  345. print_value(&proxy_object.handler(), seen_objects);
  346. }
  347. static void print_map(JS::Map const& map, HashTable<JS::Object*>& seen_objects)
  348. {
  349. print_type("Map");
  350. js_out(" {{");
  351. bool first = true;
  352. for (auto const& entry : map) {
  353. print_separator(first);
  354. print_value(entry.key, seen_objects);
  355. js_out(" => ");
  356. print_value(entry.value, seen_objects);
  357. }
  358. if (!first)
  359. js_out(" ");
  360. js_out("}}");
  361. }
  362. static void print_set(JS::Set const& set, HashTable<JS::Object*>& seen_objects)
  363. {
  364. print_type("Set");
  365. js_out(" {{");
  366. bool first = true;
  367. for (auto const& entry : set) {
  368. print_separator(first);
  369. print_value(entry.key, seen_objects);
  370. }
  371. if (!first)
  372. js_out(" ");
  373. js_out("}}");
  374. }
  375. static void print_weak_map(JS::WeakMap const& weak_map, HashTable<JS::Object*>&)
  376. {
  377. print_type("WeakMap");
  378. js_out(" ({})", weak_map.values().size());
  379. // Note: We could tell you what's actually inside, but not in insertion order.
  380. }
  381. static void print_weak_set(JS::WeakSet const& weak_set, HashTable<JS::Object*>&)
  382. {
  383. print_type("WeakSet");
  384. js_out(" ({})", weak_set.values().size());
  385. // Note: We could tell you what's actually inside, but not in insertion order.
  386. }
  387. static void print_weak_ref(JS::WeakRef const& weak_ref, HashTable<JS::Object*>& seen_objects)
  388. {
  389. print_type("WeakRef");
  390. js_out(" ");
  391. print_value(weak_ref.value().visit([](Empty) -> JS::Value { return JS::js_undefined(); }, [](auto* value) -> JS::Value { return value; }), seen_objects);
  392. }
  393. static void print_promise(JS::Promise const& promise, HashTable<JS::Object*>& seen_objects)
  394. {
  395. print_type("Promise");
  396. switch (promise.state()) {
  397. case JS::Promise::State::Pending:
  398. js_out("\n state: ");
  399. js_out("\033[36;1mPending\033[0m");
  400. break;
  401. case JS::Promise::State::Fulfilled:
  402. js_out("\n state: ");
  403. js_out("\033[32;1mFulfilled\033[0m");
  404. js_out("\n result: ");
  405. print_value(promise.result(), seen_objects);
  406. break;
  407. case JS::Promise::State::Rejected:
  408. js_out("\n state: ");
  409. js_out("\033[31;1mRejected\033[0m");
  410. js_out("\n result: ");
  411. print_value(promise.result(), seen_objects);
  412. break;
  413. default:
  414. VERIFY_NOT_REACHED();
  415. }
  416. }
  417. static void print_array_buffer(JS::ArrayBuffer const& array_buffer, HashTable<JS::Object*>& seen_objects)
  418. {
  419. auto& buffer = array_buffer.buffer();
  420. auto byte_length = array_buffer.byte_length();
  421. print_type("ArrayBuffer");
  422. js_out("\n byteLength: ");
  423. print_value(JS::Value((double)byte_length), seen_objects);
  424. if (!byte_length)
  425. return;
  426. js_outln();
  427. for (size_t i = 0; i < byte_length; ++i) {
  428. js_out("{:02x}", buffer[i]);
  429. if (i + 1 < byte_length) {
  430. if ((i + 1) % 32 == 0)
  431. js_outln();
  432. else if ((i + 1) % 16 == 0)
  433. js_out(" ");
  434. else
  435. js_out(" ");
  436. }
  437. }
  438. }
  439. static void print_shadow_realm(JS::ShadowRealm const&, HashTable<JS::Object*>&)
  440. {
  441. // Not much we can show here that would be useful. Realm pointer address?!
  442. print_type("ShadowRealm");
  443. }
  444. static void print_generator(JS::GeneratorObject const&, HashTable<JS::Object*>&)
  445. {
  446. print_type("Generator");
  447. }
  448. static void print_async_generator(JS::AsyncGenerator const&, HashTable<JS::Object*>&)
  449. {
  450. print_type("AsyncGenerator");
  451. }
  452. template<typename T>
  453. static void print_number(T number) requires IsArithmetic<T>
  454. {
  455. js_out("\033[35;1m");
  456. js_out("{}", number);
  457. js_out("\033[0m");
  458. }
  459. static void print_typed_array(JS::TypedArrayBase const& typed_array_base, HashTable<JS::Object*>& seen_objects)
  460. {
  461. auto& array_buffer = *typed_array_base.viewed_array_buffer();
  462. auto length = typed_array_base.array_length();
  463. print_type(typed_array_base.class_name());
  464. js_out("\n length: ");
  465. print_value(JS::Value(length), seen_objects);
  466. js_out("\n byteLength: ");
  467. print_value(JS::Value(typed_array_base.byte_length()), seen_objects);
  468. js_out("\n buffer: ");
  469. print_type("ArrayBuffer");
  470. if (array_buffer.is_detached())
  471. js_out(" (detached)");
  472. js_out(" @ {:p}", &array_buffer);
  473. if (!length || array_buffer.is_detached())
  474. return;
  475. js_outln();
  476. // FIXME: This kinda sucks.
  477. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  478. if (is<JS::ClassName>(typed_array_base)) { \
  479. js_out("[ "); \
  480. auto& typed_array = static_cast<JS::ClassName const&>(typed_array_base); \
  481. auto data = typed_array.data(); \
  482. for (size_t i = 0; i < length; ++i) { \
  483. if (i > 0) \
  484. js_out(", "); \
  485. print_number(data[i]); \
  486. } \
  487. js_out(" ]"); \
  488. return; \
  489. }
  490. JS_ENUMERATE_TYPED_ARRAYS
  491. #undef __JS_ENUMERATE
  492. VERIFY_NOT_REACHED();
  493. }
  494. static void print_data_view(JS::DataView const& data_view, HashTable<JS::Object*>& seen_objects)
  495. {
  496. print_type("DataView");
  497. js_out("\n byteLength: ");
  498. print_value(JS::Value(data_view.byte_length()), seen_objects);
  499. js_out("\n byteOffset: ");
  500. print_value(JS::Value(data_view.byte_offset()), seen_objects);
  501. js_out("\n buffer: ");
  502. print_type("ArrayBuffer");
  503. js_out(" @ {:p}", data_view.viewed_array_buffer());
  504. }
  505. static void print_temporal_calendar(JS::Temporal::Calendar const& calendar, HashTable<JS::Object*>& seen_objects)
  506. {
  507. print_type("Temporal.Calendar");
  508. js_out(" ");
  509. print_value(JS::js_string(calendar.vm(), calendar.identifier()), seen_objects);
  510. }
  511. static void print_temporal_duration(JS::Temporal::Duration const& duration, HashTable<JS::Object*>&)
  512. {
  513. print_type("Temporal.Duration");
  514. js_out(" \033[34;1m{} y, {} M, {} w, {} d, {} h, {} m, {} s, {} ms, {} us, {} ns\033[0m", duration.years(), duration.months(), duration.weeks(), duration.days(), duration.hours(), duration.minutes(), duration.seconds(), duration.milliseconds(), duration.microseconds(), duration.nanoseconds());
  515. }
  516. static void print_temporal_instant(JS::Temporal::Instant const& instant, HashTable<JS::Object*>& seen_objects)
  517. {
  518. print_type("Temporal.Instant");
  519. js_out(" ");
  520. // FIXME: Print human readable date and time, like in print_date() - ideally handling arbitrarily large values since we get a bigint.
  521. print_value(&instant.nanoseconds(), seen_objects);
  522. }
  523. static void print_temporal_plain_date(JS::Temporal::PlainDate const& plain_date, HashTable<JS::Object*>& seen_objects)
  524. {
  525. print_type("Temporal.PlainDate");
  526. js_out(" \033[34;1m{:04}-{:02}-{:02}\033[0m", plain_date.iso_year(), plain_date.iso_month(), plain_date.iso_day());
  527. js_out("\n calendar: ");
  528. print_value(&plain_date.calendar(), seen_objects);
  529. }
  530. static void print_temporal_plain_date_time(JS::Temporal::PlainDateTime const& plain_date_time, HashTable<JS::Object*>& seen_objects)
  531. {
  532. print_type("Temporal.PlainDateTime");
  533. js_out(" \033[34;1m{:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:03}{:03}{:03}\033[0m", plain_date_time.iso_year(), plain_date_time.iso_month(), plain_date_time.iso_day(), plain_date_time.iso_hour(), plain_date_time.iso_minute(), plain_date_time.iso_second(), plain_date_time.iso_millisecond(), plain_date_time.iso_microsecond(), plain_date_time.iso_nanosecond());
  534. js_out("\n calendar: ");
  535. print_value(&plain_date_time.calendar(), seen_objects);
  536. }
  537. static void print_temporal_plain_month_day(JS::Temporal::PlainMonthDay const& plain_month_day, HashTable<JS::Object*>& seen_objects)
  538. {
  539. print_type("Temporal.PlainMonthDay");
  540. // Also has an [[ISOYear]] internal slot, but showing that here seems rather unexpected.
  541. js_out(" \033[34;1m{:02}-{:02}\033[0m", plain_month_day.iso_month(), plain_month_day.iso_day());
  542. js_out("\n calendar: ");
  543. print_value(&plain_month_day.calendar(), seen_objects);
  544. }
  545. static void print_temporal_plain_time(JS::Temporal::PlainTime const& plain_time, HashTable<JS::Object*>& seen_objects)
  546. {
  547. print_type("Temporal.PlainTime");
  548. js_out(" \033[34;1m{:02}:{:02}:{:02}.{:03}{:03}{:03}\033[0m", plain_time.iso_hour(), plain_time.iso_minute(), plain_time.iso_second(), plain_time.iso_millisecond(), plain_time.iso_microsecond(), plain_time.iso_nanosecond());
  549. js_out("\n calendar: ");
  550. print_value(&plain_time.calendar(), seen_objects);
  551. }
  552. static void print_temporal_plain_year_month(JS::Temporal::PlainYearMonth const& plain_year_month, HashTable<JS::Object*>& seen_objects)
  553. {
  554. print_type("Temporal.PlainYearMonth");
  555. // Also has an [[ISODay]] internal slot, but showing that here seems rather unexpected.
  556. js_out(" \033[34;1m{:04}-{:02}\033[0m", plain_year_month.iso_year(), plain_year_month.iso_month());
  557. js_out("\n calendar: ");
  558. print_value(&plain_year_month.calendar(), seen_objects);
  559. }
  560. static void print_temporal_time_zone(JS::Temporal::TimeZone const& time_zone, HashTable<JS::Object*>& seen_objects)
  561. {
  562. print_type("Temporal.TimeZone");
  563. js_out(" ");
  564. print_value(JS::js_string(time_zone.vm(), time_zone.identifier()), seen_objects);
  565. if (time_zone.offset_nanoseconds().has_value()) {
  566. js_out("\n offset (ns): ");
  567. print_value(JS::Value(*time_zone.offset_nanoseconds()), seen_objects);
  568. }
  569. }
  570. static void print_temporal_zoned_date_time(JS::Temporal::ZonedDateTime const& zoned_date_time, HashTable<JS::Object*>& seen_objects)
  571. {
  572. print_type("Temporal.ZonedDateTime");
  573. js_out("\n epochNanoseconds: ");
  574. print_value(&zoned_date_time.nanoseconds(), seen_objects);
  575. js_out("\n timeZone: ");
  576. print_value(&zoned_date_time.time_zone(), seen_objects);
  577. js_out("\n calendar: ");
  578. print_value(&zoned_date_time.calendar(), seen_objects);
  579. }
  580. static void print_intl_display_names(JS::Intl::DisplayNames const& display_names, HashTable<JS::Object*>& seen_objects)
  581. {
  582. print_type("Intl.DisplayNames");
  583. js_out("\n locale: ");
  584. print_value(js_string(display_names.vm(), display_names.locale()), seen_objects);
  585. js_out("\n type: ");
  586. print_value(js_string(display_names.vm(), display_names.type_string()), seen_objects);
  587. js_out("\n style: ");
  588. print_value(js_string(display_names.vm(), display_names.style_string()), seen_objects);
  589. js_out("\n fallback: ");
  590. print_value(js_string(display_names.vm(), display_names.fallback_string()), seen_objects);
  591. if (display_names.has_language_display()) {
  592. js_out("\n languageDisplay: ");
  593. print_value(js_string(display_names.vm(), display_names.language_display_string()), seen_objects);
  594. }
  595. }
  596. static void print_intl_locale(JS::Intl::Locale const& locale, HashTable<JS::Object*>& seen_objects)
  597. {
  598. print_type("Intl.Locale");
  599. js_out("\n locale: ");
  600. print_value(js_string(locale.vm(), locale.locale()), seen_objects);
  601. if (locale.has_calendar()) {
  602. js_out("\n calendar: ");
  603. print_value(js_string(locale.vm(), locale.calendar()), seen_objects);
  604. }
  605. if (locale.has_case_first()) {
  606. js_out("\n caseFirst: ");
  607. print_value(js_string(locale.vm(), locale.case_first()), seen_objects);
  608. }
  609. if (locale.has_collation()) {
  610. js_out("\n collation: ");
  611. print_value(js_string(locale.vm(), locale.collation()), seen_objects);
  612. }
  613. if (locale.has_hour_cycle()) {
  614. js_out("\n hourCycle: ");
  615. print_value(js_string(locale.vm(), locale.hour_cycle()), seen_objects);
  616. }
  617. if (locale.has_numbering_system()) {
  618. js_out("\n numberingSystem: ");
  619. print_value(js_string(locale.vm(), locale.numbering_system()), seen_objects);
  620. }
  621. js_out("\n numeric: ");
  622. print_value(JS::Value(locale.numeric()), seen_objects);
  623. }
  624. static void print_intl_list_format(JS::Intl::ListFormat const& list_format, HashTable<JS::Object*>& seen_objects)
  625. {
  626. print_type("Intl.ListFormat");
  627. js_out("\n locale: ");
  628. print_value(js_string(list_format.vm(), list_format.locale()), seen_objects);
  629. js_out("\n type: ");
  630. print_value(js_string(list_format.vm(), list_format.type_string()), seen_objects);
  631. js_out("\n style: ");
  632. print_value(js_string(list_format.vm(), list_format.style_string()), seen_objects);
  633. }
  634. static void print_intl_number_format(JS::Intl::NumberFormat const& number_format, HashTable<JS::Object*>& seen_objects)
  635. {
  636. print_type("Intl.NumberFormat");
  637. js_out("\n locale: ");
  638. print_value(js_string(number_format.vm(), number_format.locale()), seen_objects);
  639. js_out("\n dataLocale: ");
  640. print_value(js_string(number_format.vm(), number_format.data_locale()), seen_objects);
  641. js_out("\n numberingSystem: ");
  642. print_value(js_string(number_format.vm(), number_format.numbering_system()), seen_objects);
  643. js_out("\n style: ");
  644. print_value(js_string(number_format.vm(), number_format.style_string()), seen_objects);
  645. if (number_format.has_currency()) {
  646. js_out("\n currency: ");
  647. print_value(js_string(number_format.vm(), number_format.currency()), seen_objects);
  648. }
  649. if (number_format.has_currency_display()) {
  650. js_out("\n currencyDisplay: ");
  651. print_value(js_string(number_format.vm(), number_format.currency_display_string()), seen_objects);
  652. }
  653. if (number_format.has_currency_sign()) {
  654. js_out("\n currencySign: ");
  655. print_value(js_string(number_format.vm(), number_format.currency_sign_string()), seen_objects);
  656. }
  657. if (number_format.has_unit()) {
  658. js_out("\n unit: ");
  659. print_value(js_string(number_format.vm(), number_format.unit()), seen_objects);
  660. }
  661. if (number_format.has_unit_display()) {
  662. js_out("\n unitDisplay: ");
  663. print_value(js_string(number_format.vm(), number_format.unit_display_string()), seen_objects);
  664. }
  665. js_out("\n minimumIntegerDigits: ");
  666. print_value(JS::Value(number_format.min_integer_digits()), seen_objects);
  667. if (number_format.has_min_fraction_digits()) {
  668. js_out("\n minimumFractionDigits: ");
  669. print_value(JS::Value(number_format.min_fraction_digits()), seen_objects);
  670. }
  671. if (number_format.has_max_fraction_digits()) {
  672. js_out("\n maximumFractionDigits: ");
  673. print_value(JS::Value(number_format.max_fraction_digits()), seen_objects);
  674. }
  675. if (number_format.has_min_significant_digits()) {
  676. js_out("\n minimumSignificantDigits: ");
  677. print_value(JS::Value(number_format.min_significant_digits()), seen_objects);
  678. }
  679. if (number_format.has_max_significant_digits()) {
  680. js_out("\n maximumSignificantDigits: ");
  681. print_value(JS::Value(number_format.max_significant_digits()), seen_objects);
  682. }
  683. js_out("\n useGrouping: ");
  684. print_value(number_format.use_grouping_to_value(number_format.global_object()), seen_objects);
  685. js_out("\n roundingType: ");
  686. print_value(js_string(number_format.vm(), number_format.rounding_type_string()), seen_objects);
  687. js_out("\n roundingMode: ");
  688. print_value(js_string(number_format.vm(), number_format.rounding_mode_string()), seen_objects);
  689. js_out("\n roundingIncrement: ");
  690. print_value(JS::Value(number_format.rounding_increment()), seen_objects);
  691. js_out("\n notation: ");
  692. print_value(js_string(number_format.vm(), number_format.notation_string()), seen_objects);
  693. if (number_format.has_compact_display()) {
  694. js_out("\n compactDisplay: ");
  695. print_value(js_string(number_format.vm(), number_format.compact_display_string()), seen_objects);
  696. }
  697. js_out("\n signDisplay: ");
  698. print_value(js_string(number_format.vm(), number_format.sign_display_string()), seen_objects);
  699. js_out("\n trailingZeroDisplay: ");
  700. print_value(js_string(number_format.vm(), number_format.trailing_zero_display_string()), seen_objects);
  701. }
  702. static void print_intl_date_time_format(JS::Intl::DateTimeFormat& date_time_format, HashTable<JS::Object*>& seen_objects)
  703. {
  704. print_type("Intl.DateTimeFormat");
  705. js_out("\n locale: ");
  706. print_value(js_string(date_time_format.vm(), date_time_format.locale()), seen_objects);
  707. js_out("\n pattern: ");
  708. print_value(js_string(date_time_format.vm(), date_time_format.pattern()), seen_objects);
  709. js_out("\n calendar: ");
  710. print_value(js_string(date_time_format.vm(), date_time_format.calendar()), seen_objects);
  711. js_out("\n numberingSystem: ");
  712. print_value(js_string(date_time_format.vm(), date_time_format.numbering_system()), seen_objects);
  713. if (date_time_format.has_hour_cycle()) {
  714. js_out("\n hourCycle: ");
  715. print_value(js_string(date_time_format.vm(), date_time_format.hour_cycle_string()), seen_objects);
  716. }
  717. js_out("\n timeZone: ");
  718. print_value(js_string(date_time_format.vm(), date_time_format.time_zone()), seen_objects);
  719. if (date_time_format.has_date_style()) {
  720. js_out("\n dateStyle: ");
  721. print_value(js_string(date_time_format.vm(), date_time_format.date_style_string()), seen_objects);
  722. }
  723. if (date_time_format.has_time_style()) {
  724. js_out("\n timeStyle: ");
  725. print_value(js_string(date_time_format.vm(), date_time_format.time_style_string()), seen_objects);
  726. }
  727. JS::Intl::for_each_calendar_field(date_time_format.global_object(), date_time_format, [&](auto& option, auto const& property, auto const&) -> JS::ThrowCompletionOr<void> {
  728. using ValueType = typename RemoveReference<decltype(option)>::ValueType;
  729. if (!option.has_value())
  730. return {};
  731. js_out("\n {}: ", property);
  732. if constexpr (IsIntegral<ValueType>) {
  733. print_value(JS::Value(*option), seen_objects);
  734. } else {
  735. auto name = Unicode::calendar_pattern_style_to_string(*option);
  736. print_value(js_string(date_time_format.vm(), name), seen_objects);
  737. }
  738. return {};
  739. });
  740. }
  741. static void print_intl_relative_time_format(JS::Intl::RelativeTimeFormat const& date_time_format, HashTable<JS::Object*>& seen_objects)
  742. {
  743. print_type("Intl.RelativeTimeFormat");
  744. js_out("\n locale: ");
  745. print_value(js_string(date_time_format.vm(), date_time_format.locale()), seen_objects);
  746. js_out("\n numberingSystem: ");
  747. print_value(js_string(date_time_format.vm(), date_time_format.numbering_system()), seen_objects);
  748. js_out("\n style: ");
  749. print_value(js_string(date_time_format.vm(), date_time_format.style_string()), seen_objects);
  750. js_out("\n numeric: ");
  751. print_value(js_string(date_time_format.vm(), date_time_format.numeric_string()), seen_objects);
  752. }
  753. static void print_intl_plural_rules(JS::Intl::PluralRules const& plural_rules, HashTable<JS::Object*>& seen_objects)
  754. {
  755. print_type("Intl.PluralRules");
  756. js_out("\n locale: ");
  757. print_value(js_string(plural_rules.vm(), plural_rules.locale()), seen_objects);
  758. js_out("\n type: ");
  759. print_value(js_string(plural_rules.vm(), plural_rules.type_string()), seen_objects);
  760. js_out("\n minimumIntegerDigits: ");
  761. print_value(JS::Value(plural_rules.min_integer_digits()), seen_objects);
  762. if (plural_rules.has_min_fraction_digits()) {
  763. js_out("\n minimumFractionDigits: ");
  764. print_value(JS::Value(plural_rules.min_fraction_digits()), seen_objects);
  765. }
  766. if (plural_rules.has_max_fraction_digits()) {
  767. js_out("\n maximumFractionDigits: ");
  768. print_value(JS::Value(plural_rules.max_fraction_digits()), seen_objects);
  769. }
  770. if (plural_rules.has_min_significant_digits()) {
  771. js_out("\n minimumSignificantDigits: ");
  772. print_value(JS::Value(plural_rules.min_significant_digits()), seen_objects);
  773. }
  774. if (plural_rules.has_max_significant_digits()) {
  775. js_out("\n maximumSignificantDigits: ");
  776. print_value(JS::Value(plural_rules.max_significant_digits()), seen_objects);
  777. }
  778. js_out("\n roundingType: ");
  779. print_value(js_string(plural_rules.vm(), plural_rules.rounding_type_string()), seen_objects);
  780. }
  781. static void print_intl_collator(JS::Intl::Collator const& collator, HashTable<JS::Object*>& seen_objects)
  782. {
  783. print_type("Intl.Collator");
  784. out("\n locale: ");
  785. print_value(js_string(collator.vm(), collator.locale()), seen_objects);
  786. out("\n usage: ");
  787. print_value(js_string(collator.vm(), collator.usage_string()), seen_objects);
  788. out("\n sensitivity: ");
  789. print_value(js_string(collator.vm(), collator.sensitivity_string()), seen_objects);
  790. out("\n caseFirst: ");
  791. print_value(js_string(collator.vm(), collator.case_first_string()), seen_objects);
  792. out("\n collation: ");
  793. print_value(js_string(collator.vm(), collator.collation()), seen_objects);
  794. out("\n ignorePunctuation: ");
  795. print_value(JS::Value(collator.ignore_punctuation()), seen_objects);
  796. out("\n numeric: ");
  797. print_value(JS::Value(collator.numeric()), seen_objects);
  798. }
  799. static void print_intl_segmenter(JS::Intl::Segmenter const& segmenter, HashTable<JS::Object*>& seen_objects)
  800. {
  801. print_type("Intl.Segmenter");
  802. out("\n locale: ");
  803. print_value(js_string(segmenter.vm(), segmenter.locale()), seen_objects);
  804. out("\n granularity: ");
  805. print_value(js_string(segmenter.vm(), segmenter.segmenter_granularity_string()), seen_objects);
  806. }
  807. static void print_intl_segments(JS::Intl::Segments const& segments, HashTable<JS::Object*>& seen_objects)
  808. {
  809. print_type("Segments");
  810. out("\n string: ");
  811. print_value(js_string(segments.vm(), segments.segments_string()), seen_objects);
  812. out("\n segmenter: ");
  813. print_value(&segments.segments_segmenter(), seen_objects);
  814. }
  815. static void print_intl_duration_format(JS::Intl::DurationFormat const& duration_format, HashTable<JS::Object*>& seen_objects)
  816. {
  817. print_type("Intl.DurationFormat");
  818. out("\n locale: ");
  819. print_value(js_string(duration_format.vm(), duration_format.locale()), seen_objects);
  820. out("\n dataLocale: ");
  821. print_value(js_string(duration_format.vm(), duration_format.data_locale()), seen_objects);
  822. out("\n numberingSystem: ");
  823. print_value(js_string(duration_format.vm(), duration_format.numbering_system()), seen_objects);
  824. out("\n style: ");
  825. print_value(js_string(duration_format.vm(), duration_format.style_string()), seen_objects);
  826. out("\n years: ");
  827. print_value(js_string(duration_format.vm(), duration_format.years_style_string()), seen_objects);
  828. out("\n yearsDisplay: ");
  829. print_value(js_string(duration_format.vm(), duration_format.years_display_string()), seen_objects);
  830. out("\n months: ");
  831. print_value(js_string(duration_format.vm(), duration_format.months_style_string()), seen_objects);
  832. out("\n monthsDisplay: ");
  833. print_value(js_string(duration_format.vm(), duration_format.months_display_string()), seen_objects);
  834. out("\n weeks: ");
  835. print_value(js_string(duration_format.vm(), duration_format.weeks_style_string()), seen_objects);
  836. out("\n weeksDisplay: ");
  837. print_value(js_string(duration_format.vm(), duration_format.weeks_display_string()), seen_objects);
  838. out("\n days: ");
  839. print_value(js_string(duration_format.vm(), duration_format.days_style_string()), seen_objects);
  840. out("\n daysDisplay: ");
  841. print_value(js_string(duration_format.vm(), duration_format.days_display_string()), seen_objects);
  842. out("\n hours: ");
  843. print_value(js_string(duration_format.vm(), duration_format.hours_style_string()), seen_objects);
  844. out("\n hoursDisplay: ");
  845. print_value(js_string(duration_format.vm(), duration_format.hours_display_string()), seen_objects);
  846. out("\n minutes: ");
  847. print_value(js_string(duration_format.vm(), duration_format.minutes_style_string()), seen_objects);
  848. out("\n minutesDisplay: ");
  849. print_value(js_string(duration_format.vm(), duration_format.minutes_display_string()), seen_objects);
  850. out("\n seconds: ");
  851. print_value(js_string(duration_format.vm(), duration_format.seconds_style_string()), seen_objects);
  852. out("\n secondsDisplay: ");
  853. print_value(js_string(duration_format.vm(), duration_format.seconds_display_string()), seen_objects);
  854. out("\n milliseconds: ");
  855. print_value(js_string(duration_format.vm(), duration_format.milliseconds_style_string()), seen_objects);
  856. out("\n millisecondsDisplay: ");
  857. print_value(js_string(duration_format.vm(), duration_format.milliseconds_display_string()), seen_objects);
  858. out("\n microseconds: ");
  859. print_value(js_string(duration_format.vm(), duration_format.microseconds_style_string()), seen_objects);
  860. out("\n microsecondsDisplay: ");
  861. print_value(js_string(duration_format.vm(), duration_format.microseconds_display_string()), seen_objects);
  862. out("\n nanoseconds: ");
  863. print_value(js_string(duration_format.vm(), duration_format.nanoseconds_style_string()), seen_objects);
  864. out("\n nanosecondsDisplay: ");
  865. print_value(js_string(duration_format.vm(), duration_format.nanoseconds_display_string()), seen_objects);
  866. if (duration_format.has_fractional_digits()) {
  867. out("\n fractionalDigits: ");
  868. print_value(JS::Value(duration_format.fractional_digits()), seen_objects);
  869. }
  870. }
  871. static void print_boolean_object(JS::BooleanObject const& boolean_object, HashTable<JS::Object*>& seen_objects)
  872. {
  873. print_type("Boolean");
  874. js_out(" ");
  875. print_value(JS::Value(boolean_object.boolean()), seen_objects);
  876. }
  877. static void print_number_object(JS::NumberObject const& number_object, HashTable<JS::Object*>& seen_objects)
  878. {
  879. print_type("Number");
  880. js_out(" ");
  881. print_value(JS::Value(number_object.number()), seen_objects);
  882. }
  883. static void print_string_object(JS::StringObject const& string_object, HashTable<JS::Object*>& seen_objects)
  884. {
  885. print_type("String");
  886. js_out(" ");
  887. print_value(&string_object.primitive_string(), seen_objects);
  888. }
  889. static void print_value(JS::Value value, HashTable<JS::Object*>& seen_objects)
  890. {
  891. if (value.is_empty()) {
  892. js_out("\033[34;1m<empty>\033[0m");
  893. return;
  894. }
  895. if (value.is_object()) {
  896. if (seen_objects.contains(&value.as_object())) {
  897. // FIXME: Maybe we should only do this for circular references,
  898. // not for all reoccurring objects.
  899. js_out("<already printed Object {}>", &value.as_object());
  900. return;
  901. }
  902. seen_objects.set(&value.as_object());
  903. }
  904. if (value.is_object()) {
  905. auto& object = value.as_object();
  906. if (is<JS::Array>(object))
  907. return print_array(static_cast<JS::Array&>(object), seen_objects);
  908. if (object.is_function())
  909. return print_function(static_cast<JS::FunctionObject&>(object), seen_objects);
  910. if (is<JS::Date>(object))
  911. return print_date(static_cast<JS::Date&>(object), seen_objects);
  912. if (is<JS::Error>(object))
  913. return print_error(object, seen_objects);
  914. auto prototype_or_error = object.internal_get_prototype_of();
  915. if (prototype_or_error.has_value() && prototype_or_error.value() == object.global_object().error_prototype())
  916. return print_error(object, seen_objects);
  917. if (is<JS::RegExpObject>(object))
  918. return print_regexp_object(static_cast<JS::RegExpObject&>(object), seen_objects);
  919. if (is<JS::Map>(object))
  920. return print_map(static_cast<JS::Map&>(object), seen_objects);
  921. if (is<JS::Set>(object))
  922. return print_set(static_cast<JS::Set&>(object), seen_objects);
  923. if (is<JS::WeakMap>(object))
  924. return print_weak_map(static_cast<JS::WeakMap&>(object), seen_objects);
  925. if (is<JS::WeakSet>(object))
  926. return print_weak_set(static_cast<JS::WeakSet&>(object), seen_objects);
  927. if (is<JS::WeakRef>(object))
  928. return print_weak_ref(static_cast<JS::WeakRef&>(object), seen_objects);
  929. if (is<JS::DataView>(object))
  930. return print_data_view(static_cast<JS::DataView&>(object), seen_objects);
  931. if (is<JS::ProxyObject>(object))
  932. return print_proxy_object(static_cast<JS::ProxyObject&>(object), seen_objects);
  933. if (is<JS::Promise>(object))
  934. return print_promise(static_cast<JS::Promise&>(object), seen_objects);
  935. if (is<JS::ArrayBuffer>(object))
  936. return print_array_buffer(static_cast<JS::ArrayBuffer&>(object), seen_objects);
  937. if (is<JS::ShadowRealm>(object))
  938. return print_shadow_realm(static_cast<JS::ShadowRealm&>(object), seen_objects);
  939. if (is<JS::GeneratorObject>(object))
  940. return print_generator(static_cast<JS::GeneratorObject&>(object), seen_objects);
  941. if (is<JS::AsyncGenerator>(object))
  942. return print_async_generator(static_cast<JS::AsyncGenerator&>(object), seen_objects);
  943. if (object.is_typed_array())
  944. return print_typed_array(static_cast<JS::TypedArrayBase&>(object), seen_objects);
  945. if (is<JS::BooleanObject>(object))
  946. return print_boolean_object(static_cast<JS::BooleanObject&>(object), seen_objects);
  947. if (is<JS::NumberObject>(object))
  948. return print_number_object(static_cast<JS::NumberObject&>(object), seen_objects);
  949. if (is<JS::StringObject>(object))
  950. return print_string_object(static_cast<JS::StringObject&>(object), seen_objects);
  951. if (is<JS::Temporal::Calendar>(object))
  952. return print_temporal_calendar(static_cast<JS::Temporal::Calendar&>(object), seen_objects);
  953. if (is<JS::Temporal::Duration>(object))
  954. return print_temporal_duration(static_cast<JS::Temporal::Duration&>(object), seen_objects);
  955. if (is<JS::Temporal::Instant>(object))
  956. return print_temporal_instant(static_cast<JS::Temporal::Instant&>(object), seen_objects);
  957. if (is<JS::Temporal::PlainDate>(object))
  958. return print_temporal_plain_date(static_cast<JS::Temporal::PlainDate&>(object), seen_objects);
  959. if (is<JS::Temporal::PlainDateTime>(object))
  960. return print_temporal_plain_date_time(static_cast<JS::Temporal::PlainDateTime&>(object), seen_objects);
  961. if (is<JS::Temporal::PlainMonthDay>(object))
  962. return print_temporal_plain_month_day(static_cast<JS::Temporal::PlainMonthDay&>(object), seen_objects);
  963. if (is<JS::Temporal::PlainTime>(object))
  964. return print_temporal_plain_time(static_cast<JS::Temporal::PlainTime&>(object), seen_objects);
  965. if (is<JS::Temporal::PlainYearMonth>(object))
  966. return print_temporal_plain_year_month(static_cast<JS::Temporal::PlainYearMonth&>(object), seen_objects);
  967. if (is<JS::Temporal::TimeZone>(object))
  968. return print_temporal_time_zone(static_cast<JS::Temporal::TimeZone&>(object), seen_objects);
  969. if (is<JS::Temporal::ZonedDateTime>(object))
  970. return print_temporal_zoned_date_time(static_cast<JS::Temporal::ZonedDateTime&>(object), seen_objects);
  971. if (is<JS::Intl::DisplayNames>(object))
  972. return print_intl_display_names(static_cast<JS::Intl::DisplayNames&>(object), seen_objects);
  973. if (is<JS::Intl::Locale>(object))
  974. return print_intl_locale(static_cast<JS::Intl::Locale&>(object), seen_objects);
  975. if (is<JS::Intl::ListFormat>(object))
  976. return print_intl_list_format(static_cast<JS::Intl::ListFormat&>(object), seen_objects);
  977. if (is<JS::Intl::NumberFormat>(object))
  978. return print_intl_number_format(static_cast<JS::Intl::NumberFormat&>(object), seen_objects);
  979. if (is<JS::Intl::DateTimeFormat>(object))
  980. return print_intl_date_time_format(static_cast<JS::Intl::DateTimeFormat&>(object), seen_objects);
  981. if (is<JS::Intl::RelativeTimeFormat>(object))
  982. return print_intl_relative_time_format(static_cast<JS::Intl::RelativeTimeFormat&>(object), seen_objects);
  983. if (is<JS::Intl::PluralRules>(object))
  984. return print_intl_plural_rules(static_cast<JS::Intl::PluralRules&>(object), seen_objects);
  985. if (is<JS::Intl::Collator>(object))
  986. return print_intl_collator(static_cast<JS::Intl::Collator&>(object), seen_objects);
  987. if (is<JS::Intl::Segmenter>(object))
  988. return print_intl_segmenter(static_cast<JS::Intl::Segmenter&>(object), seen_objects);
  989. if (is<JS::Intl::Segments>(object))
  990. return print_intl_segments(static_cast<JS::Intl::Segments&>(object), seen_objects);
  991. if (is<JS::Intl::DurationFormat>(object))
  992. return print_intl_duration_format(static_cast<JS::Intl::DurationFormat&>(object), seen_objects);
  993. return print_object(object, seen_objects);
  994. }
  995. if (value.is_string())
  996. js_out("\033[32;1m");
  997. else if (value.is_number() || value.is_bigint())
  998. js_out("\033[35;1m");
  999. else if (value.is_boolean())
  1000. js_out("\033[33;1m");
  1001. else if (value.is_null())
  1002. js_out("\033[33;1m");
  1003. else if (value.is_undefined())
  1004. js_out("\033[34;1m");
  1005. if (value.is_string())
  1006. js_out("\"");
  1007. else if (value.is_negative_zero())
  1008. js_out("-");
  1009. js_out("{}", value.to_string_without_side_effects());
  1010. if (value.is_string())
  1011. js_out("\"");
  1012. js_out("\033[0m");
  1013. }
  1014. static void print(JS::Value value)
  1015. {
  1016. HashTable<JS::Object*> seen_objects;
  1017. print_value(value, seen_objects);
  1018. js_outln();
  1019. }
  1020. static bool write_to_file(String const& path)
  1021. {
  1022. int fd = open(path.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  1023. for (size_t i = 0; i < g_repl_statements.size(); i++) {
  1024. auto line = g_repl_statements[i];
  1025. if (line.length() && i != g_repl_statements.size() - 1) {
  1026. ssize_t nwritten = write(fd, line.characters(), line.length());
  1027. if (nwritten < 0) {
  1028. close(fd);
  1029. return false;
  1030. }
  1031. }
  1032. if (i != g_repl_statements.size() - 1) {
  1033. char ch = '\n';
  1034. ssize_t nwritten = write(fd, &ch, 1);
  1035. if (nwritten != 1) {
  1036. perror("write");
  1037. close(fd);
  1038. return false;
  1039. }
  1040. }
  1041. }
  1042. close(fd);
  1043. return true;
  1044. }
  1045. static bool parse_and_run(JS::Interpreter& interpreter, StringView source, StringView source_name)
  1046. {
  1047. enum class ReturnEarly {
  1048. No,
  1049. Yes,
  1050. };
  1051. JS::ThrowCompletionOr<JS::Value> result { JS::js_undefined() };
  1052. auto run_script_or_module = [&](auto& script_or_module) {
  1053. if (s_dump_ast)
  1054. script_or_module->parse_node().dump(0);
  1055. if (JS::Bytecode::g_dump_bytecode || s_run_bytecode) {
  1056. auto executable_result = JS::Bytecode::Generator::generate(script_or_module->parse_node());
  1057. if (executable_result.is_error()) {
  1058. result = g_vm->throw_completion<JS::InternalError>(interpreter.global_object(), executable_result.error().to_string());
  1059. return ReturnEarly::No;
  1060. }
  1061. auto executable = executable_result.release_value();
  1062. executable->name = source_name;
  1063. if (s_opt_bytecode) {
  1064. auto& passes = JS::Bytecode::Interpreter::optimization_pipeline();
  1065. passes.perform(*executable);
  1066. dbgln("Optimisation passes took {}us", passes.elapsed());
  1067. }
  1068. if (JS::Bytecode::g_dump_bytecode)
  1069. executable->dump();
  1070. if (s_run_bytecode) {
  1071. JS::Bytecode::Interpreter bytecode_interpreter(interpreter.global_object(), interpreter.realm());
  1072. auto result_or_error = bytecode_interpreter.run_and_return_frame(*executable, nullptr);
  1073. if (result_or_error.value.is_error())
  1074. result = result_or_error.value.release_error();
  1075. else
  1076. result = result_or_error.frame->registers[0];
  1077. } else {
  1078. return ReturnEarly::Yes;
  1079. }
  1080. } else {
  1081. result = interpreter.run(*script_or_module);
  1082. }
  1083. return ReturnEarly::No;
  1084. };
  1085. if (!s_as_module) {
  1086. auto script_or_error = JS::Script::parse(source, interpreter.realm(), source_name);
  1087. if (script_or_error.is_error()) {
  1088. auto error = script_or_error.error()[0];
  1089. auto hint = error.source_location_hint(source);
  1090. if (!hint.is_empty())
  1091. outln("{}", hint);
  1092. outln("{}", error.to_string());
  1093. result = interpreter.vm().throw_completion<JS::SyntaxError>(interpreter.global_object(), error.to_string());
  1094. } else {
  1095. auto return_early = run_script_or_module(script_or_error.value());
  1096. if (return_early == ReturnEarly::Yes)
  1097. return true;
  1098. }
  1099. } else {
  1100. auto module_or_error = JS::SourceTextModule::parse(source, interpreter.realm(), source_name);
  1101. if (module_or_error.is_error()) {
  1102. auto error = module_or_error.error()[0];
  1103. auto hint = error.source_location_hint(source);
  1104. if (!hint.is_empty())
  1105. outln("{}", hint);
  1106. outln(error.to_string());
  1107. result = interpreter.vm().throw_completion<JS::SyntaxError>(interpreter.global_object(), error.to_string());
  1108. } else {
  1109. auto return_early = run_script_or_module(module_or_error.value());
  1110. if (return_early == ReturnEarly::Yes)
  1111. return true;
  1112. }
  1113. }
  1114. auto handle_exception = [&](JS::Value thrown_value) {
  1115. js_out("Uncaught exception: ");
  1116. print(thrown_value);
  1117. if (!thrown_value.is_object() || !is<JS::Error>(thrown_value.as_object()))
  1118. return;
  1119. auto& traceback = static_cast<JS::Error const&>(thrown_value.as_object()).traceback();
  1120. if (traceback.size() > 1) {
  1121. unsigned repetitions = 0;
  1122. for (size_t i = 0; i < traceback.size(); ++i) {
  1123. auto& traceback_frame = traceback[i];
  1124. if (i + 1 < traceback.size()) {
  1125. auto& next_traceback_frame = traceback[i + 1];
  1126. if (next_traceback_frame.function_name == traceback_frame.function_name) {
  1127. repetitions++;
  1128. continue;
  1129. }
  1130. }
  1131. if (repetitions > 4) {
  1132. // If more than 5 (1 + >4) consecutive function calls with the same name, print
  1133. // the name only once and show the number of repetitions instead. This prevents
  1134. // printing ridiculously large call stacks of recursive functions.
  1135. js_outln(" -> {}", traceback_frame.function_name);
  1136. js_outln(" {} more calls", repetitions);
  1137. } else {
  1138. for (size_t j = 0; j < repetitions + 1; ++j)
  1139. js_outln(" -> {}", traceback_frame.function_name);
  1140. }
  1141. repetitions = 0;
  1142. }
  1143. }
  1144. };
  1145. if (!result.is_error())
  1146. g_last_value = JS::make_handle(result.value());
  1147. if (result.is_error()) {
  1148. VERIFY(result.throw_completion().value().has_value());
  1149. handle_exception(*result.release_error().value());
  1150. return false;
  1151. } else if (s_print_last_result) {
  1152. print(result.value());
  1153. }
  1154. return true;
  1155. }
  1156. static JS::ThrowCompletionOr<JS::Value> load_ini_impl(JS::VM& vm, JS::GlobalObject& global_object)
  1157. {
  1158. auto filename = TRY(vm.argument(0).to_string(global_object));
  1159. auto file = Core::File::construct(filename);
  1160. if (!file->open(Core::OpenMode::ReadOnly))
  1161. return vm.throw_completion<JS::Error>(global_object, String::formatted("Failed to open '{}': {}", filename, file->error_string()));
  1162. auto config_file = MUST(Core::ConfigFile::open(filename, file->fd()));
  1163. auto* object = JS::Object::create(global_object, global_object.object_prototype());
  1164. for (auto const& group : config_file->groups()) {
  1165. auto* group_object = JS::Object::create(global_object, global_object.object_prototype());
  1166. for (auto const& key : config_file->keys(group)) {
  1167. auto entry = config_file->read_entry(group, key);
  1168. group_object->define_direct_property(key, js_string(vm, move(entry)), JS::Attribute::Enumerable | JS::Attribute::Configurable | JS::Attribute::Writable);
  1169. }
  1170. object->define_direct_property(group, group_object, JS::Attribute::Enumerable | JS::Attribute::Configurable | JS::Attribute::Writable);
  1171. }
  1172. return object;
  1173. }
  1174. static JS::ThrowCompletionOr<JS::Value> load_json_impl(JS::VM& vm, JS::GlobalObject& global_object)
  1175. {
  1176. auto filename = TRY(vm.argument(0).to_string(global_object));
  1177. auto file = Core::File::construct(filename);
  1178. if (!file->open(Core::OpenMode::ReadOnly))
  1179. return vm.throw_completion<JS::Error>(global_object, String::formatted("Failed to open '{}': {}", filename, file->error_string()));
  1180. auto file_contents = file->read_all();
  1181. auto json = JsonValue::from_string(file_contents);
  1182. if (json.is_error())
  1183. return vm.throw_completion<JS::SyntaxError>(global_object, JS::ErrorType::JsonMalformed);
  1184. return JS::JSONObject::parse_json_value(global_object, json.value());
  1185. }
  1186. void ReplObject::initialize_global_object()
  1187. {
  1188. Base::initialize_global_object();
  1189. define_direct_property("global", this, JS::Attribute::Enumerable);
  1190. u8 attr = JS::Attribute::Configurable | JS::Attribute::Writable | JS::Attribute::Enumerable;
  1191. define_native_function("exit", exit_interpreter, 0, attr);
  1192. define_native_function("help", repl_help, 0, attr);
  1193. define_native_function("save", save_to_file, 1, attr);
  1194. define_native_function("loadINI", load_ini, 1, attr);
  1195. define_native_function("loadJSON", load_json, 1, attr);
  1196. define_native_function("print", print, 1, attr);
  1197. define_native_accessor(
  1198. "_",
  1199. [](JS::VM&, JS::GlobalObject&) {
  1200. return g_last_value.value();
  1201. },
  1202. [](JS::VM& vm, JS::GlobalObject& global_object) -> JS::ThrowCompletionOr<JS::Value> {
  1203. VERIFY(is<ReplObject>(global_object));
  1204. outln("Disable writing last value to '_'");
  1205. // We must delete first otherwise this setter gets called recursively.
  1206. TRY(global_object.internal_delete(JS::PropertyKey { "_" }));
  1207. auto value = vm.argument(0);
  1208. TRY(global_object.internal_set(JS::PropertyKey { "_" }, value, &global_object));
  1209. return value;
  1210. },
  1211. attr);
  1212. }
  1213. JS_DEFINE_NATIVE_FUNCTION(ReplObject::save_to_file)
  1214. {
  1215. if (!vm.argument_count())
  1216. return JS::Value(false);
  1217. String save_path = vm.argument(0).to_string_without_side_effects();
  1218. if (write_to_file(save_path)) {
  1219. return JS::Value(true);
  1220. }
  1221. return JS::Value(false);
  1222. }
  1223. JS_DEFINE_NATIVE_FUNCTION(ReplObject::exit_interpreter)
  1224. {
  1225. if (!vm.argument_count())
  1226. exit(0);
  1227. exit(TRY(vm.argument(0).to_number(global_object)).as_double());
  1228. }
  1229. JS_DEFINE_NATIVE_FUNCTION(ReplObject::repl_help)
  1230. {
  1231. js_outln("REPL commands:");
  1232. js_outln(" exit(code): exit the REPL with specified code. Defaults to 0.");
  1233. js_outln(" help(): display this menu");
  1234. js_outln(" loadINI(file): load the given file as INI.");
  1235. js_outln(" loadJSON(file): load the given file as JSON.");
  1236. js_outln(" print(value): pretty-print the given JS value.");
  1237. js_outln(" save(file): write REPL input history to the given file. For example: save(\"foo.txt\")");
  1238. return JS::js_undefined();
  1239. }
  1240. JS_DEFINE_NATIVE_FUNCTION(ReplObject::load_ini)
  1241. {
  1242. return load_ini_impl(vm, global_object);
  1243. }
  1244. JS_DEFINE_NATIVE_FUNCTION(ReplObject::load_json)
  1245. {
  1246. return load_json_impl(vm, global_object);
  1247. }
  1248. JS_DEFINE_NATIVE_FUNCTION(ReplObject::print)
  1249. {
  1250. ::print(vm.argument(0));
  1251. return JS::js_undefined();
  1252. }
  1253. void ScriptObject::initialize_global_object()
  1254. {
  1255. Base::initialize_global_object();
  1256. define_direct_property("global", this, JS::Attribute::Enumerable);
  1257. u8 attr = JS::Attribute::Configurable | JS::Attribute::Writable | JS::Attribute::Enumerable;
  1258. define_native_function("loadINI", load_ini, 1, attr);
  1259. define_native_function("loadJSON", load_json, 1, attr);
  1260. define_native_function("print", print, 1, attr);
  1261. }
  1262. JS_DEFINE_NATIVE_FUNCTION(ScriptObject::load_ini)
  1263. {
  1264. return load_ini_impl(vm, global_object);
  1265. }
  1266. JS_DEFINE_NATIVE_FUNCTION(ScriptObject::load_json)
  1267. {
  1268. return load_json_impl(vm, global_object);
  1269. }
  1270. JS_DEFINE_NATIVE_FUNCTION(ScriptObject::print)
  1271. {
  1272. ::print(vm.argument(0));
  1273. return JS::js_undefined();
  1274. }
  1275. static void repl(JS::Interpreter& interpreter)
  1276. {
  1277. while (!s_fail_repl) {
  1278. String piece = read_next_piece();
  1279. if (Utf8View { piece }.trim(JS::whitespace_characters).is_empty())
  1280. continue;
  1281. g_repl_statements.append(piece);
  1282. parse_and_run(interpreter, piece, "REPL"sv);
  1283. }
  1284. }
  1285. static Function<void()> interrupt_interpreter;
  1286. static void sigint_handler()
  1287. {
  1288. interrupt_interpreter();
  1289. }
  1290. class ReplConsoleClient final : public JS::ConsoleClient {
  1291. public:
  1292. ReplConsoleClient(JS::Console& console)
  1293. : ConsoleClient(console)
  1294. {
  1295. }
  1296. virtual void clear() override
  1297. {
  1298. js_out("\033[3J\033[H\033[2J");
  1299. m_group_stack_depth = 0;
  1300. fflush(stdout);
  1301. }
  1302. virtual void end_group() override
  1303. {
  1304. if (m_group_stack_depth > 0)
  1305. m_group_stack_depth--;
  1306. }
  1307. // 2.3. Printer(logLevel, args[, options]), https://console.spec.whatwg.org/#printer
  1308. virtual JS::ThrowCompletionOr<JS::Value> printer(JS::Console::LogLevel log_level, PrinterArguments arguments) override
  1309. {
  1310. String indent = String::repeated(" "sv, m_group_stack_depth);
  1311. if (log_level == JS::Console::LogLevel::Trace) {
  1312. auto trace = arguments.get<JS::Console::Trace>();
  1313. StringBuilder builder;
  1314. if (!trace.label.is_empty())
  1315. builder.appendff("{}\033[36;1m{}\033[0m\n", indent, trace.label);
  1316. for (auto& function_name : trace.stack)
  1317. builder.appendff("{}-> {}\n", indent, function_name);
  1318. js_outln("{}", builder.string_view());
  1319. return JS::js_undefined();
  1320. }
  1321. if (log_level == JS::Console::LogLevel::Group || log_level == JS::Console::LogLevel::GroupCollapsed) {
  1322. auto group = arguments.get<JS::Console::Group>();
  1323. js_outln("{}\033[36;1m{}\033[0m", indent, group.label);
  1324. m_group_stack_depth++;
  1325. return JS::js_undefined();
  1326. }
  1327. auto output = String::join(' ', arguments.get<JS::MarkedVector<JS::Value>>());
  1328. m_console.output_debug_message(log_level, output);
  1329. switch (log_level) {
  1330. case JS::Console::LogLevel::Debug:
  1331. js_outln("{}\033[36;1m{}\033[0m", indent, output);
  1332. break;
  1333. case JS::Console::LogLevel::Error:
  1334. case JS::Console::LogLevel::Assert:
  1335. js_outln("{}\033[31;1m{}\033[0m", indent, output);
  1336. break;
  1337. case JS::Console::LogLevel::Info:
  1338. js_outln("{}(i) {}", indent, output);
  1339. break;
  1340. case JS::Console::LogLevel::Log:
  1341. js_outln("{}{}", indent, output);
  1342. break;
  1343. case JS::Console::LogLevel::Warn:
  1344. case JS::Console::LogLevel::CountReset:
  1345. js_outln("{}\033[33;1m{}\033[0m", indent, output);
  1346. break;
  1347. default:
  1348. js_outln("{}{}", indent, output);
  1349. break;
  1350. }
  1351. return JS::js_undefined();
  1352. }
  1353. private:
  1354. int m_group_stack_depth { 0 };
  1355. };
  1356. ErrorOr<int> serenity_main(Main::Arguments arguments)
  1357. {
  1358. #ifdef __serenity__
  1359. TRY(Core::System::pledge("stdio rpath wpath cpath tty sigaction"));
  1360. #endif
  1361. bool gc_on_every_allocation = false;
  1362. bool disable_syntax_highlight = false;
  1363. StringView evaluate_script;
  1364. Vector<StringView> script_paths;
  1365. Core::ArgsParser args_parser;
  1366. args_parser.set_general_help("This is a JavaScript interpreter.");
  1367. args_parser.add_option(s_dump_ast, "Dump the AST", "dump-ast", 'A');
  1368. args_parser.add_option(JS::Bytecode::g_dump_bytecode, "Dump the bytecode", "dump-bytecode", 'd');
  1369. args_parser.add_option(s_run_bytecode, "Run the bytecode", "run-bytecode", 'b');
  1370. args_parser.add_option(s_opt_bytecode, "Optimize the bytecode", "optimize-bytecode", 'p');
  1371. args_parser.add_option(s_as_module, "Treat as module", "as-module", 'm');
  1372. args_parser.add_option(s_print_last_result, "Print last result", "print-last-result", 'l');
  1373. args_parser.add_option(s_strip_ansi, "Disable ANSI colors", "disable-ansi-colors", 'i');
  1374. args_parser.add_option(s_disable_source_location_hints, "Disable source location hints", "disable-source-location-hints", 'h');
  1375. args_parser.add_option(gc_on_every_allocation, "GC on every allocation", "gc-on-every-allocation", 'g');
  1376. args_parser.add_option(disable_syntax_highlight, "Disable live syntax highlighting", "no-syntax-highlight", 's');
  1377. args_parser.add_option(evaluate_script, "Evaluate argument as a script", "evaluate", 'c', "script");
  1378. args_parser.add_positional_argument(script_paths, "Path to script files", "scripts", Core::ArgsParser::Required::No);
  1379. args_parser.parse(arguments);
  1380. bool syntax_highlight = !disable_syntax_highlight;
  1381. g_vm = JS::VM::create();
  1382. g_vm->enable_default_host_import_module_dynamically_hook();
  1383. // NOTE: These will print out both warnings when using something like Promise.reject().catch(...) -
  1384. // which is, as far as I can tell, correct - a promise is created, rejected without handler, and a
  1385. // handler then attached to it. The Node.js REPL doesn't warn in this case, so it's something we
  1386. // might want to revisit at a later point and disable warnings for promises created this way.
  1387. g_vm->on_promise_unhandled_rejection = [](auto& promise) {
  1388. // FIXME: Optionally make print_value() to print to stderr
  1389. js_out("WARNING: A promise was rejected without any handlers");
  1390. js_out(" (result: ");
  1391. HashTable<JS::Object*> seen_objects;
  1392. print_value(promise.result(), seen_objects);
  1393. js_outln(")");
  1394. };
  1395. g_vm->on_promise_rejection_handled = [](auto& promise) {
  1396. // FIXME: Optionally make print_value() to print to stderr
  1397. js_out("WARNING: A handler was added to an already rejected promise");
  1398. js_out(" (result: ");
  1399. HashTable<JS::Object*> seen_objects;
  1400. print_value(promise.result(), seen_objects);
  1401. js_outln(")");
  1402. };
  1403. OwnPtr<JS::Interpreter> interpreter;
  1404. // FIXME: Figure out some way to interrupt the interpreter now that vm.exception() is gone.
  1405. if (evaluate_script.is_empty() && script_paths.is_empty()) {
  1406. s_print_last_result = true;
  1407. interpreter = JS::Interpreter::create<ReplObject>(*g_vm);
  1408. ReplConsoleClient console_client(interpreter->global_object().console());
  1409. interpreter->global_object().console().set_client(console_client);
  1410. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  1411. auto& global_environment = interpreter->realm().global_environment();
  1412. s_editor = Line::Editor::construct();
  1413. s_editor->load_history(s_history_path);
  1414. signal(SIGINT, [](int) {
  1415. if (!s_editor->is_editing())
  1416. sigint_handler();
  1417. s_editor->save_history(s_history_path);
  1418. });
  1419. s_editor->on_display_refresh = [syntax_highlight](Line::Editor& editor) {
  1420. auto stylize = [&](Line::Span span, Line::Style styles) {
  1421. if (syntax_highlight)
  1422. editor.stylize(span, styles);
  1423. };
  1424. editor.strip_styles();
  1425. size_t open_indents = s_repl_line_level;
  1426. auto line = editor.line();
  1427. JS::Lexer lexer(line);
  1428. bool indenters_starting_line = true;
  1429. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  1430. auto length = Utf8View { token.value() }.length();
  1431. auto start = token.offset();
  1432. auto end = start + length;
  1433. if (indenters_starting_line) {
  1434. if (token.type() != JS::TokenType::ParenClose && token.type() != JS::TokenType::BracketClose && token.type() != JS::TokenType::CurlyClose) {
  1435. indenters_starting_line = false;
  1436. } else {
  1437. --open_indents;
  1438. }
  1439. }
  1440. switch (token.category()) {
  1441. case JS::TokenCategory::Invalid:
  1442. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Red), Line::Style::Underline });
  1443. break;
  1444. case JS::TokenCategory::Number:
  1445. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Magenta) });
  1446. break;
  1447. case JS::TokenCategory::String:
  1448. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Green), Line::Style::Bold });
  1449. break;
  1450. case JS::TokenCategory::Punctuation:
  1451. break;
  1452. case JS::TokenCategory::Operator:
  1453. break;
  1454. case JS::TokenCategory::Keyword:
  1455. switch (token.type()) {
  1456. case JS::TokenType::BoolLiteral:
  1457. case JS::TokenType::NullLiteral:
  1458. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow), Line::Style::Bold });
  1459. break;
  1460. default:
  1461. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Blue), Line::Style::Bold });
  1462. break;
  1463. }
  1464. break;
  1465. case JS::TokenCategory::ControlKeyword:
  1466. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan), Line::Style::Italic });
  1467. break;
  1468. case JS::TokenCategory::Identifier:
  1469. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::White), Line::Style::Bold });
  1470. break;
  1471. default:
  1472. break;
  1473. }
  1474. }
  1475. editor.set_prompt(prompt_for_level(open_indents));
  1476. };
  1477. auto complete = [&interpreter, &global_environment](Line::Editor const& editor) -> Vector<Line::CompletionSuggestion> {
  1478. auto line = editor.line(editor.cursor());
  1479. JS::Lexer lexer { line };
  1480. enum {
  1481. Initial,
  1482. CompleteVariable,
  1483. CompleteNullProperty,
  1484. CompleteProperty,
  1485. } mode { Initial };
  1486. StringView variable_name;
  1487. StringView property_name;
  1488. // we're only going to complete either
  1489. // - <N>
  1490. // where N is part of the name of a variable
  1491. // - <N>.<P>
  1492. // where N is the complete name of a variable and
  1493. // P is part of the name of one of its properties
  1494. auto js_token = lexer.next();
  1495. for (; js_token.type() != JS::TokenType::Eof; js_token = lexer.next()) {
  1496. switch (mode) {
  1497. case CompleteVariable:
  1498. switch (js_token.type()) {
  1499. case JS::TokenType::Period:
  1500. // ...<name> <dot>
  1501. mode = CompleteNullProperty;
  1502. break;
  1503. default:
  1504. // not a dot, reset back to initial
  1505. mode = Initial;
  1506. break;
  1507. }
  1508. break;
  1509. case CompleteNullProperty:
  1510. if (js_token.is_identifier_name()) {
  1511. // ...<name> <dot> <name>
  1512. mode = CompleteProperty;
  1513. property_name = js_token.value();
  1514. } else {
  1515. mode = Initial;
  1516. }
  1517. break;
  1518. case CompleteProperty:
  1519. // something came after the property access, reset to initial
  1520. case Initial:
  1521. if (js_token.type() == JS::TokenType::Identifier) {
  1522. // ...<name>...
  1523. mode = CompleteVariable;
  1524. variable_name = js_token.value();
  1525. } else {
  1526. mode = Initial;
  1527. }
  1528. break;
  1529. }
  1530. }
  1531. bool last_token_has_trivia = js_token.trivia().length() > 0;
  1532. if (mode == CompleteNullProperty) {
  1533. mode = CompleteProperty;
  1534. property_name = ""sv;
  1535. last_token_has_trivia = false; // <name> <dot> [tab] is sensible to complete.
  1536. }
  1537. if (mode == Initial || last_token_has_trivia)
  1538. return {}; // we do not know how to complete this
  1539. Vector<Line::CompletionSuggestion> results;
  1540. Function<void(JS::Shape const&, StringView)> list_all_properties = [&results, &list_all_properties](JS::Shape const& shape, auto property_pattern) {
  1541. for (auto const& descriptor : shape.property_table()) {
  1542. if (!descriptor.key.is_string())
  1543. continue;
  1544. auto key = descriptor.key.as_string();
  1545. if (key.view().starts_with(property_pattern)) {
  1546. Line::CompletionSuggestion completion { key, Line::CompletionSuggestion::ForSearch };
  1547. if (!results.contains_slow(completion)) { // hide duplicates
  1548. results.append(String(key));
  1549. results.last().invariant_offset = property_pattern.length();
  1550. }
  1551. }
  1552. }
  1553. if (auto const* prototype = shape.prototype()) {
  1554. list_all_properties(prototype->shape(), property_pattern);
  1555. }
  1556. };
  1557. switch (mode) {
  1558. case CompleteProperty: {
  1559. auto reference_or_error = g_vm->resolve_binding(variable_name, &global_environment);
  1560. if (reference_or_error.is_error())
  1561. return {};
  1562. auto value_or_error = reference_or_error.value().get_value(interpreter->global_object());
  1563. if (value_or_error.is_error())
  1564. return {};
  1565. auto variable = value_or_error.value();
  1566. VERIFY(!variable.is_empty());
  1567. if (!variable.is_object())
  1568. break;
  1569. auto const* object = MUST(variable.to_object(interpreter->global_object()));
  1570. auto const& shape = object->shape();
  1571. list_all_properties(shape, property_name);
  1572. break;
  1573. }
  1574. case CompleteVariable: {
  1575. auto const& variable = interpreter->global_object();
  1576. list_all_properties(variable.shape(), variable_name);
  1577. for (auto const& name : global_environment.declarative_record().bindings()) {
  1578. if (name.starts_with(variable_name)) {
  1579. results.empend(name);
  1580. results.last().invariant_offset = variable_name.length();
  1581. }
  1582. }
  1583. break;
  1584. }
  1585. default:
  1586. VERIFY_NOT_REACHED();
  1587. }
  1588. return results;
  1589. };
  1590. s_editor->on_tab_complete = move(complete);
  1591. repl(*interpreter);
  1592. s_editor->save_history(s_history_path);
  1593. } else {
  1594. interpreter = JS::Interpreter::create<ScriptObject>(*g_vm);
  1595. ReplConsoleClient console_client(interpreter->global_object().console());
  1596. interpreter->global_object().console().set_client(console_client);
  1597. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  1598. signal(SIGINT, [](int) {
  1599. sigint_handler();
  1600. });
  1601. StringBuilder builder;
  1602. StringView source_name;
  1603. if (evaluate_script.is_empty()) {
  1604. if (script_paths.size() > 1)
  1605. warnln("Warning: Multiple files supplied, this will concatenate the sources and resolve modules as if it was the first file");
  1606. for (auto& path : script_paths) {
  1607. auto file = TRY(Core::File::open(path, Core::OpenMode::ReadOnly));
  1608. auto file_contents = file->read_all();
  1609. auto source = StringView { file_contents };
  1610. if (Utf8View { file_contents }.validate()) {
  1611. builder.append(source);
  1612. } else {
  1613. auto* decoder = TextCodec::decoder_for("windows-1252");
  1614. VERIFY(decoder);
  1615. auto utf8_source = TextCodec::convert_input_to_utf8_using_given_decoder_unless_there_is_a_byte_order_mark(*decoder, source);
  1616. builder.append(utf8_source);
  1617. }
  1618. }
  1619. source_name = script_paths[0];
  1620. } else {
  1621. builder.append(evaluate_script);
  1622. source_name = "eval"sv;
  1623. }
  1624. // We resolve modules as if it is the first file
  1625. if (!parse_and_run(*interpreter, builder.string_view(), source_name))
  1626. return 1;
  1627. }
  1628. return 0;
  1629. }