js.cpp 61 KB

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