js.cpp 65 KB

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