js.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498
  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. if (is<JS::RegExpObject>(object))
  727. return print_regexp_object(object, seen_objects);
  728. if (is<JS::Map>(object))
  729. return print_map(object, seen_objects);
  730. if (is<JS::Set>(object))
  731. return print_set(object, seen_objects);
  732. if (is<JS::DataView>(object))
  733. return print_data_view(object, seen_objects);
  734. if (is<JS::ProxyObject>(object))
  735. return print_proxy_object(object, seen_objects);
  736. if (is<JS::Promise>(object))
  737. return print_promise(object, seen_objects);
  738. if (is<JS::ArrayBuffer>(object))
  739. return print_array_buffer(object, seen_objects);
  740. if (is<JS::ShadowRealm>(object))
  741. return print_shadow_realm(object, seen_objects);
  742. if (object.is_typed_array())
  743. return print_typed_array(object, seen_objects);
  744. if (is<JS::StringObject>(object))
  745. return print_primitive_wrapper_object("String", object, seen_objects);
  746. if (is<JS::NumberObject>(object))
  747. return print_primitive_wrapper_object("Number", object, seen_objects);
  748. if (is<JS::BooleanObject>(object))
  749. return print_primitive_wrapper_object("Boolean", object, seen_objects);
  750. if (is<JS::Temporal::Calendar>(object))
  751. return print_temporal_calendar(object, seen_objects);
  752. if (is<JS::Temporal::Duration>(object))
  753. return print_temporal_duration(object, seen_objects);
  754. if (is<JS::Temporal::Instant>(object))
  755. return print_temporal_instant(object, seen_objects);
  756. if (is<JS::Temporal::PlainDate>(object))
  757. return print_temporal_plain_date(object, seen_objects);
  758. if (is<JS::Temporal::PlainDateTime>(object))
  759. return print_temporal_plain_date_time(object, seen_objects);
  760. if (is<JS::Temporal::PlainMonthDay>(object))
  761. return print_temporal_plain_month_day(object, seen_objects);
  762. if (is<JS::Temporal::PlainTime>(object))
  763. return print_temporal_plain_time(object, seen_objects);
  764. if (is<JS::Temporal::PlainYearMonth>(object))
  765. return print_temporal_plain_year_month(object, seen_objects);
  766. if (is<JS::Temporal::TimeZone>(object))
  767. return print_temporal_time_zone(object, seen_objects);
  768. if (is<JS::Temporal::ZonedDateTime>(object))
  769. return print_temporal_zoned_date_time(object, seen_objects);
  770. if (is<JS::Intl::DisplayNames>(object))
  771. return print_intl_display_names(object, seen_objects);
  772. if (is<JS::Intl::Locale>(object))
  773. return print_intl_locale(object, seen_objects);
  774. if (is<JS::Intl::ListFormat>(object))
  775. return print_intl_list_format(object, seen_objects);
  776. if (is<JS::Intl::NumberFormat>(object))
  777. return print_intl_number_format(object, seen_objects);
  778. if (is<JS::Intl::DateTimeFormat>(object))
  779. return print_intl_date_time_format(object, seen_objects);
  780. return print_object(object, seen_objects);
  781. }
  782. if (value.is_string())
  783. js_out("\033[32;1m");
  784. else if (value.is_number() || value.is_bigint())
  785. js_out("\033[35;1m");
  786. else if (value.is_boolean())
  787. js_out("\033[33;1m");
  788. else if (value.is_null())
  789. js_out("\033[33;1m");
  790. else if (value.is_undefined())
  791. js_out("\033[34;1m");
  792. if (value.is_string())
  793. js_out("\"");
  794. else if (value.is_negative_zero())
  795. js_out("-");
  796. js_out("{}", value.to_string_without_side_effects());
  797. if (value.is_string())
  798. js_out("\"");
  799. js_out("\033[0m");
  800. }
  801. static void print(JS::Value value)
  802. {
  803. HashTable<JS::Object*> seen_objects;
  804. print_value(value, seen_objects);
  805. js_outln();
  806. }
  807. static bool write_to_file(String const& path)
  808. {
  809. int fd = open(path.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  810. for (size_t i = 0; i < repl_statements.size(); i++) {
  811. auto line = repl_statements[i];
  812. if (line.length() && i != repl_statements.size() - 1) {
  813. ssize_t nwritten = write(fd, line.characters(), line.length());
  814. if (nwritten < 0) {
  815. close(fd);
  816. return false;
  817. }
  818. }
  819. if (i != repl_statements.size() - 1) {
  820. char ch = '\n';
  821. ssize_t nwritten = write(fd, &ch, 1);
  822. if (nwritten != 1) {
  823. perror("write");
  824. close(fd);
  825. return false;
  826. }
  827. }
  828. }
  829. close(fd);
  830. return true;
  831. }
  832. static bool parse_and_run(JS::Interpreter& interpreter, StringView source, StringView source_name)
  833. {
  834. auto program_type = s_as_module ? JS::Program::Type::Module : JS::Program::Type::Script;
  835. auto parser = JS::Parser(JS::Lexer(source), program_type);
  836. auto program = parser.parse_program();
  837. if (s_dump_ast)
  838. program->dump(0);
  839. if (parser.has_errors()) {
  840. auto error = parser.errors()[0];
  841. if (!s_disable_source_location_hints) {
  842. auto hint = error.source_location_hint(source);
  843. if (!hint.is_empty())
  844. js_outln("{}", hint);
  845. }
  846. vm->throw_exception<JS::SyntaxError>(interpreter.global_object(), error.to_string());
  847. } else {
  848. if (JS::Bytecode::g_dump_bytecode || s_run_bytecode) {
  849. auto executable = JS::Bytecode::Generator::generate(*program);
  850. executable.name = source_name;
  851. if (s_opt_bytecode) {
  852. auto& passes = JS::Bytecode::Interpreter::optimization_pipeline();
  853. passes.perform(executable);
  854. dbgln("Optimisation passes took {}us", passes.elapsed());
  855. }
  856. if (JS::Bytecode::g_dump_bytecode)
  857. executable.dump();
  858. if (s_run_bytecode) {
  859. JS::Bytecode::Interpreter bytecode_interpreter(interpreter.global_object(), interpreter.realm());
  860. auto result = bytecode_interpreter.run(executable);
  861. // Since all the error handling code uses vm.exception() we just rethrow any exception we got here.
  862. if (result.is_error())
  863. vm->throw_exception(interpreter.global_object(), *result.throw_completion().value());
  864. } else {
  865. return true;
  866. }
  867. } else {
  868. interpreter.run(interpreter.global_object(), *program);
  869. }
  870. }
  871. auto handle_exception = [&] {
  872. auto* exception = vm->exception();
  873. vm->clear_exception();
  874. js_out("Uncaught exception: ");
  875. print(exception->value());
  876. auto& traceback = exception->traceback();
  877. if (traceback.size() > 1) {
  878. unsigned repetitions = 0;
  879. for (size_t i = 0; i < traceback.size(); ++i) {
  880. auto& traceback_frame = traceback[i];
  881. if (i + 1 < traceback.size()) {
  882. auto& next_traceback_frame = traceback[i + 1];
  883. if (next_traceback_frame.function_name == traceback_frame.function_name) {
  884. repetitions++;
  885. continue;
  886. }
  887. }
  888. if (repetitions > 4) {
  889. // If more than 5 (1 + >4) consecutive function calls with the same name, print
  890. // the name only once and show the number of repetitions instead. This prevents
  891. // printing ridiculously large call stacks of recursive functions.
  892. js_outln(" -> {}", traceback_frame.function_name);
  893. js_outln(" {} more calls", repetitions);
  894. } else {
  895. for (size_t j = 0; j < repetitions + 1; ++j)
  896. js_outln(" -> {}", traceback_frame.function_name);
  897. }
  898. repetitions = 0;
  899. }
  900. }
  901. };
  902. if (vm->exception()) {
  903. handle_exception();
  904. return false;
  905. }
  906. if (s_print_last_result)
  907. print(vm->last_value());
  908. if (vm->exception()) {
  909. handle_exception();
  910. return false;
  911. }
  912. return true;
  913. }
  914. static JS::ThrowCompletionOr<JS::Value> load_file_impl(JS::VM& vm, JS::GlobalObject& global_object)
  915. {
  916. auto filename = TRY(vm.argument(0).to_string(global_object));
  917. auto file = Core::File::construct(filename);
  918. if (!file->open(Core::OpenMode::ReadOnly))
  919. return vm.throw_completion<JS::Error>(global_object, String::formatted("Failed to open '{}': {}", filename, file->error_string()));
  920. auto file_contents = file->read_all();
  921. auto source = StringView { file_contents };
  922. auto parser = JS::Parser(JS::Lexer(source));
  923. auto program = parser.parse_program();
  924. if (parser.has_errors()) {
  925. auto& error = parser.errors()[0];
  926. return vm.throw_completion<JS::SyntaxError>(global_object, error.to_string());
  927. }
  928. // FIXME: Use eval()-like semantics and execute in current scope?
  929. vm.interpreter().run(global_object, *program);
  930. return JS::js_undefined();
  931. }
  932. static JS::ThrowCompletionOr<JS::Value> load_json_impl(JS::VM& vm, JS::GlobalObject& global_object)
  933. {
  934. auto filename = TRY(vm.argument(0).to_string(global_object));
  935. auto file = Core::File::construct(filename);
  936. if (!file->open(Core::OpenMode::ReadOnly))
  937. return vm.throw_completion<JS::Error>(global_object, String::formatted("Failed to open '{}': {}", filename, file->error_string()));
  938. auto file_contents = file->read_all();
  939. auto json = JsonValue::from_string(file_contents);
  940. if (json.is_error())
  941. return vm.throw_completion<JS::SyntaxError>(global_object, JS::ErrorType::JsonMalformed);
  942. return JS::JSONObject::parse_json_value(global_object, json.value());
  943. }
  944. void ReplObject::initialize_global_object()
  945. {
  946. Base::initialize_global_object();
  947. define_direct_property("global", this, JS::Attribute::Enumerable);
  948. u8 attr = JS::Attribute::Configurable | JS::Attribute::Writable | JS::Attribute::Enumerable;
  949. define_native_function("exit", exit_interpreter, 0, attr);
  950. define_native_function("help", repl_help, 0, attr);
  951. define_native_function("load", load_file, 1, attr);
  952. define_native_function("save", save_to_file, 1, attr);
  953. define_native_function("loadJSON", load_json, 1, attr);
  954. }
  955. JS_DEFINE_NATIVE_FUNCTION(ReplObject::save_to_file)
  956. {
  957. if (!vm.argument_count())
  958. return JS::Value(false);
  959. String save_path = vm.argument(0).to_string_without_side_effects();
  960. StringView path = StringView(save_path.characters());
  961. if (write_to_file(path)) {
  962. return JS::Value(true);
  963. }
  964. return JS::Value(false);
  965. }
  966. JS_DEFINE_NATIVE_FUNCTION(ReplObject::exit_interpreter)
  967. {
  968. if (!vm.argument_count())
  969. exit(0);
  970. exit(TRY(vm.argument(0).to_number(global_object)).as_double());
  971. }
  972. JS_DEFINE_NATIVE_FUNCTION(ReplObject::repl_help)
  973. {
  974. js_outln("REPL commands:");
  975. js_outln(" exit(code): exit the REPL with specified code. Defaults to 0.");
  976. js_outln(" help(): display this menu");
  977. js_outln(" load(file): load given JS file into running session. For example: load(\"foo.js\")");
  978. js_outln(" save(file): write REPL input history to the given file. For example: save(\"foo.txt\")");
  979. return JS::js_undefined();
  980. }
  981. JS_DEFINE_NATIVE_FUNCTION(ReplObject::load_file)
  982. {
  983. return load_file_impl(vm, global_object);
  984. }
  985. JS_DEFINE_NATIVE_FUNCTION(ReplObject::load_json)
  986. {
  987. return load_json_impl(vm, global_object);
  988. }
  989. void ScriptObject::initialize_global_object()
  990. {
  991. Base::initialize_global_object();
  992. define_direct_property("global", this, JS::Attribute::Enumerable);
  993. u8 attr = JS::Attribute::Configurable | JS::Attribute::Writable | JS::Attribute::Enumerable;
  994. define_native_function("load", load_file, 1, attr);
  995. define_native_function("loadJSON", load_json, 1, attr);
  996. }
  997. JS_DEFINE_NATIVE_FUNCTION(ScriptObject::load_file)
  998. {
  999. return load_file_impl(vm, global_object);
  1000. }
  1001. JS_DEFINE_NATIVE_FUNCTION(ScriptObject::load_json)
  1002. {
  1003. return load_json_impl(vm, global_object);
  1004. }
  1005. static void repl(JS::Interpreter& interpreter)
  1006. {
  1007. while (!s_fail_repl) {
  1008. String piece = read_next_piece();
  1009. if (piece.is_empty())
  1010. continue;
  1011. repl_statements.append(piece);
  1012. parse_and_run(interpreter, piece, "REPL");
  1013. }
  1014. }
  1015. static Function<void()> interrupt_interpreter;
  1016. static void sigint_handler()
  1017. {
  1018. interrupt_interpreter();
  1019. }
  1020. class ReplConsoleClient final : public JS::ConsoleClient {
  1021. public:
  1022. ReplConsoleClient(JS::Console& console)
  1023. : ConsoleClient(console)
  1024. {
  1025. }
  1026. virtual void clear() override
  1027. {
  1028. js_out("\033[3J\033[H\033[2J");
  1029. m_group_stack_depth = 0;
  1030. fflush(stdout);
  1031. }
  1032. virtual void end_group() override
  1033. {
  1034. if (m_group_stack_depth > 0)
  1035. m_group_stack_depth--;
  1036. }
  1037. // 2.3. Printer(logLevel, args[, options]), https://console.spec.whatwg.org/#printer
  1038. virtual JS::ThrowCompletionOr<JS::Value> printer(JS::Console::LogLevel log_level, PrinterArguments arguments) override
  1039. {
  1040. String indent = String::repeated(" ", m_group_stack_depth);
  1041. if (log_level == JS::Console::LogLevel::Trace) {
  1042. auto trace = arguments.get<JS::Console::Trace>();
  1043. StringBuilder builder;
  1044. if (!trace.label.is_empty())
  1045. builder.appendff("{}\033[36;1m{}\033[0m\n", indent, trace.label);
  1046. for (auto& function_name : trace.stack)
  1047. builder.appendff("{}-> {}\n", indent, function_name);
  1048. js_outln("{}", builder.string_view());
  1049. return JS::js_undefined();
  1050. }
  1051. if (log_level == JS::Console::LogLevel::Group || log_level == JS::Console::LogLevel::GroupCollapsed) {
  1052. auto group = arguments.get<JS::Console::Group>();
  1053. js_outln("{}\033[36;1m{}\033[0m", indent, group.label);
  1054. m_group_stack_depth++;
  1055. return JS::js_undefined();
  1056. }
  1057. auto output = String::join(" ", arguments.get<Vector<JS::Value>>());
  1058. m_console.output_debug_message(log_level, output);
  1059. switch (log_level) {
  1060. case JS::Console::LogLevel::Debug:
  1061. js_outln("{}\033[36;1m{}\033[0m", indent, output);
  1062. break;
  1063. case JS::Console::LogLevel::Error:
  1064. case JS::Console::LogLevel::Assert:
  1065. js_outln("{}\033[31;1m{}\033[0m", indent, output);
  1066. break;
  1067. case JS::Console::LogLevel::Info:
  1068. js_outln("{}(i) {}", indent, output);
  1069. break;
  1070. case JS::Console::LogLevel::Log:
  1071. js_outln("{}{}", indent, output);
  1072. break;
  1073. case JS::Console::LogLevel::Warn:
  1074. case JS::Console::LogLevel::CountReset:
  1075. js_outln("{}\033[33;1m{}\033[0m", indent, output);
  1076. break;
  1077. default:
  1078. js_outln("{}{}", indent, output);
  1079. break;
  1080. }
  1081. return JS::js_undefined();
  1082. }
  1083. private:
  1084. int m_group_stack_depth { 0 };
  1085. };
  1086. ErrorOr<int> serenity_main(Main::Arguments arguments)
  1087. {
  1088. #ifdef __serenity__
  1089. TRY(Core::System::pledge("stdio rpath wpath cpath tty sigaction"));
  1090. #endif
  1091. bool gc_on_every_allocation = false;
  1092. bool disable_syntax_highlight = false;
  1093. Vector<StringView> script_paths;
  1094. Core::ArgsParser args_parser;
  1095. args_parser.set_general_help("This is a JavaScript interpreter.");
  1096. args_parser.add_option(s_dump_ast, "Dump the AST", "dump-ast", 'A');
  1097. args_parser.add_option(JS::Bytecode::g_dump_bytecode, "Dump the bytecode", "dump-bytecode", 'd');
  1098. args_parser.add_option(s_run_bytecode, "Run the bytecode", "run-bytecode", 'b');
  1099. args_parser.add_option(s_opt_bytecode, "Optimize the bytecode", "optimize-bytecode", 'p');
  1100. args_parser.add_option(s_as_module, "Treat as module", "as-module", 'm');
  1101. args_parser.add_option(s_print_last_result, "Print last result", "print-last-result", 'l');
  1102. args_parser.add_option(s_strip_ansi, "Disable ANSI colors", "disable-ansi-colors", 'c');
  1103. args_parser.add_option(s_disable_source_location_hints, "Disable source location hints", "disable-source-location-hints", 'h');
  1104. args_parser.add_option(gc_on_every_allocation, "GC on every allocation", "gc-on-every-allocation", 'g');
  1105. #ifdef JS_TRACK_ZOMBIE_CELLS
  1106. bool zombify_dead_cells = false;
  1107. args_parser.add_option(zombify_dead_cells, "Zombify dead cells (to catch missing GC marks)", "zombify-dead-cells", 'z');
  1108. #endif
  1109. args_parser.add_option(disable_syntax_highlight, "Disable live syntax highlighting", "no-syntax-highlight", 's');
  1110. args_parser.add_positional_argument(script_paths, "Path to script files", "scripts", Core::ArgsParser::Required::No);
  1111. args_parser.parse(arguments);
  1112. bool syntax_highlight = !disable_syntax_highlight;
  1113. vm = JS::VM::create();
  1114. // NOTE: These will print out both warnings when using something like Promise.reject().catch(...) -
  1115. // which is, as far as I can tell, correct - a promise is created, rejected without handler, and a
  1116. // handler then attached to it. The Node.js REPL doesn't warn in this case, so it's something we
  1117. // might want to revisit at a later point and disable warnings for promises created this way.
  1118. vm->on_promise_unhandled_rejection = [](auto& promise) {
  1119. // FIXME: Optionally make print_value() to print to stderr
  1120. js_out("WARNING: A promise was rejected without any handlers");
  1121. js_out(" (result: ");
  1122. HashTable<JS::Object*> seen_objects;
  1123. print_value(promise.result(), seen_objects);
  1124. js_outln(")");
  1125. };
  1126. vm->on_promise_rejection_handled = [](auto& promise) {
  1127. // FIXME: Optionally make print_value() to print to stderr
  1128. js_out("WARNING: A handler was added to an already rejected promise");
  1129. js_out(" (result: ");
  1130. HashTable<JS::Object*> seen_objects;
  1131. print_value(promise.result(), seen_objects);
  1132. js_outln(")");
  1133. };
  1134. OwnPtr<JS::Interpreter> interpreter;
  1135. interrupt_interpreter = [&] {
  1136. auto error = JS::Error::create(interpreter->global_object(), "Received SIGINT");
  1137. vm->throw_exception(interpreter->global_object(), error);
  1138. };
  1139. if (script_paths.is_empty()) {
  1140. s_print_last_result = true;
  1141. interpreter = JS::Interpreter::create<ReplObject>(*vm);
  1142. ReplConsoleClient console_client(interpreter->global_object().console());
  1143. interpreter->global_object().console().set_client(console_client);
  1144. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  1145. #ifdef JS_TRACK_ZOMBIE_CELLS
  1146. interpreter->heap().set_zombify_dead_cells(zombify_dead_cells);
  1147. #endif
  1148. interpreter->vm().set_underscore_is_last_value(true);
  1149. auto& global_environment = interpreter->realm().global_environment();
  1150. s_editor = Line::Editor::construct();
  1151. s_editor->load_history(s_history_path);
  1152. signal(SIGINT, [](int) {
  1153. if (!s_editor->is_editing())
  1154. sigint_handler();
  1155. s_editor->save_history(s_history_path);
  1156. });
  1157. s_editor->on_display_refresh = [syntax_highlight](Line::Editor& editor) {
  1158. auto stylize = [&](Line::Span span, Line::Style styles) {
  1159. if (syntax_highlight)
  1160. editor.stylize(span, styles);
  1161. };
  1162. editor.strip_styles();
  1163. size_t open_indents = s_repl_line_level;
  1164. auto line = editor.line();
  1165. JS::Lexer lexer(line);
  1166. bool indenters_starting_line = true;
  1167. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  1168. auto length = Utf8View { token.value() }.length();
  1169. auto start = token.line_column() - 1;
  1170. auto end = start + length;
  1171. if (indenters_starting_line) {
  1172. if (token.type() != JS::TokenType::ParenClose && token.type() != JS::TokenType::BracketClose && token.type() != JS::TokenType::CurlyClose) {
  1173. indenters_starting_line = false;
  1174. } else {
  1175. --open_indents;
  1176. }
  1177. }
  1178. switch (token.category()) {
  1179. case JS::TokenCategory::Invalid:
  1180. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Red), Line::Style::Underline });
  1181. break;
  1182. case JS::TokenCategory::Number:
  1183. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Magenta) });
  1184. break;
  1185. case JS::TokenCategory::String:
  1186. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Green), Line::Style::Bold });
  1187. break;
  1188. case JS::TokenCategory::Punctuation:
  1189. break;
  1190. case JS::TokenCategory::Operator:
  1191. break;
  1192. case JS::TokenCategory::Keyword:
  1193. switch (token.type()) {
  1194. case JS::TokenType::BoolLiteral:
  1195. case JS::TokenType::NullLiteral:
  1196. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow), Line::Style::Bold });
  1197. break;
  1198. default:
  1199. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Blue), Line::Style::Bold });
  1200. break;
  1201. }
  1202. break;
  1203. case JS::TokenCategory::ControlKeyword:
  1204. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan), Line::Style::Italic });
  1205. break;
  1206. case JS::TokenCategory::Identifier:
  1207. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::White), Line::Style::Bold });
  1208. break;
  1209. default:
  1210. break;
  1211. }
  1212. }
  1213. editor.set_prompt(prompt_for_level(open_indents));
  1214. };
  1215. auto complete = [&interpreter, &global_environment](Line::Editor const& editor) -> Vector<Line::CompletionSuggestion> {
  1216. auto line = editor.line(editor.cursor());
  1217. JS::Lexer lexer { line };
  1218. enum {
  1219. Initial,
  1220. CompleteVariable,
  1221. CompleteNullProperty,
  1222. CompleteProperty,
  1223. } mode { Initial };
  1224. StringView variable_name;
  1225. StringView property_name;
  1226. // we're only going to complete either
  1227. // - <N>
  1228. // where N is part of the name of a variable
  1229. // - <N>.<P>
  1230. // where N is the complete name of a variable and
  1231. // P is part of the name of one of its properties
  1232. auto js_token = lexer.next();
  1233. for (; js_token.type() != JS::TokenType::Eof; js_token = lexer.next()) {
  1234. switch (mode) {
  1235. case CompleteVariable:
  1236. switch (js_token.type()) {
  1237. case JS::TokenType::Period:
  1238. // ...<name> <dot>
  1239. mode = CompleteNullProperty;
  1240. break;
  1241. default:
  1242. // not a dot, reset back to initial
  1243. mode = Initial;
  1244. break;
  1245. }
  1246. break;
  1247. case CompleteNullProperty:
  1248. if (js_token.is_identifier_name()) {
  1249. // ...<name> <dot> <name>
  1250. mode = CompleteProperty;
  1251. property_name = js_token.value();
  1252. } else {
  1253. mode = Initial;
  1254. }
  1255. break;
  1256. case CompleteProperty:
  1257. // something came after the property access, reset to initial
  1258. case Initial:
  1259. if (js_token.type() == JS::TokenType::Identifier) {
  1260. // ...<name>...
  1261. mode = CompleteVariable;
  1262. variable_name = js_token.value();
  1263. } else {
  1264. mode = Initial;
  1265. }
  1266. break;
  1267. }
  1268. }
  1269. bool last_token_has_trivia = js_token.trivia().length() > 0;
  1270. if (mode == CompleteNullProperty) {
  1271. mode = CompleteProperty;
  1272. property_name = "";
  1273. last_token_has_trivia = false; // <name> <dot> [tab] is sensible to complete.
  1274. }
  1275. if (mode == Initial || last_token_has_trivia)
  1276. return {}; // we do not know how to complete this
  1277. Vector<Line::CompletionSuggestion> results;
  1278. Function<void(JS::Shape const&, StringView)> list_all_properties = [&results, &list_all_properties](JS::Shape const& shape, auto property_pattern) {
  1279. for (auto const& descriptor : shape.property_table()) {
  1280. if (!descriptor.key.is_string())
  1281. continue;
  1282. auto key = descriptor.key.as_string();
  1283. if (key.view().starts_with(property_pattern)) {
  1284. Line::CompletionSuggestion completion { key, Line::CompletionSuggestion::ForSearch };
  1285. if (!results.contains_slow(completion)) { // hide duplicates
  1286. results.append(String(key));
  1287. }
  1288. }
  1289. }
  1290. if (auto const* prototype = shape.prototype()) {
  1291. list_all_properties(prototype->shape(), property_pattern);
  1292. }
  1293. };
  1294. switch (mode) {
  1295. case CompleteProperty: {
  1296. auto reference_or_error = vm->resolve_binding(variable_name, &global_environment);
  1297. if (reference_or_error.is_error())
  1298. return {};
  1299. auto value_or_error = reference_or_error.value().get_value(interpreter->global_object());
  1300. if (value_or_error.is_error())
  1301. return {};
  1302. auto variable = value_or_error.value();
  1303. VERIFY(!variable.is_empty());
  1304. if (!variable.is_object())
  1305. break;
  1306. auto const* object = MUST(variable.to_object(interpreter->global_object()));
  1307. auto const& shape = object->shape();
  1308. list_all_properties(shape, property_name);
  1309. if (results.size())
  1310. editor.suggest(property_name.length());
  1311. break;
  1312. }
  1313. case CompleteVariable: {
  1314. auto const& variable = interpreter->global_object();
  1315. list_all_properties(variable.shape(), variable_name);
  1316. for (String& name : global_environment.declarative_record().bindings()) {
  1317. if (name.starts_with(variable_name))
  1318. results.empend(name);
  1319. }
  1320. if (results.size())
  1321. editor.suggest(variable_name.length());
  1322. break;
  1323. }
  1324. default:
  1325. VERIFY_NOT_REACHED();
  1326. }
  1327. return results;
  1328. };
  1329. s_editor->on_tab_complete = move(complete);
  1330. repl(*interpreter);
  1331. s_editor->save_history(s_history_path);
  1332. } else {
  1333. interpreter = JS::Interpreter::create<ScriptObject>(*vm);
  1334. ReplConsoleClient console_client(interpreter->global_object().console());
  1335. interpreter->global_object().console().set_client(console_client);
  1336. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  1337. #ifdef JS_TRACK_ZOMBIE_CELLS
  1338. interpreter->heap().set_zombify_dead_cells(zombify_dead_cells);
  1339. #endif
  1340. signal(SIGINT, [](int) {
  1341. sigint_handler();
  1342. });
  1343. StringBuilder builder;
  1344. for (auto& path : script_paths) {
  1345. auto file = TRY(Core::File::open(path, Core::OpenMode::ReadOnly));
  1346. auto file_contents = file->read_all();
  1347. auto source = StringView { file_contents };
  1348. builder.append(source);
  1349. }
  1350. StringBuilder source_name_builder;
  1351. source_name_builder.join(", ", script_paths);
  1352. if (!parse_and_run(*interpreter, builder.string_view(), source_name_builder.string_view()))
  1353. return 1;
  1354. }
  1355. return 0;
  1356. }