js.cpp 58 KB

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