js.cpp 58 KB

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