js.cpp 62 KB

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