js.cpp 68 KB

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