js.cpp 59 KB

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