js.cpp 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645
  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. print_type("Map");
  322. js_out(" {{");
  323. bool first = true;
  324. for (auto& entry : map) {
  325. print_separator(first);
  326. print_value(entry.key, seen_objects);
  327. js_out(" => ");
  328. print_value(entry.value, seen_objects);
  329. }
  330. if (!first)
  331. js_out(" ");
  332. js_out("}}");
  333. }
  334. static void print_set(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  335. {
  336. auto& set = static_cast<JS::Set const&>(object);
  337. print_type("Set");
  338. js_out(" {{");
  339. bool first = true;
  340. for (auto& entry : set) {
  341. print_separator(first);
  342. print_value(entry.key, seen_objects);
  343. }
  344. if (!first)
  345. js_out(" ");
  346. js_out("}}");
  347. }
  348. static void print_promise(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  349. {
  350. auto& promise = static_cast<JS::Promise const&>(object);
  351. print_type("Promise");
  352. switch (promise.state()) {
  353. case JS::Promise::State::Pending:
  354. js_out("\n state: ");
  355. js_out("\033[36;1mPending\033[0m");
  356. break;
  357. case JS::Promise::State::Fulfilled:
  358. js_out("\n state: ");
  359. js_out("\033[32;1mFulfilled\033[0m");
  360. js_out("\n result: ");
  361. print_value(promise.result(), seen_objects);
  362. break;
  363. case JS::Promise::State::Rejected:
  364. js_out("\n state: ");
  365. js_out("\033[31;1mRejected\033[0m");
  366. js_out("\n result: ");
  367. print_value(promise.result(), seen_objects);
  368. break;
  369. default:
  370. VERIFY_NOT_REACHED();
  371. }
  372. }
  373. static void print_array_buffer(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  374. {
  375. auto& array_buffer = static_cast<JS::ArrayBuffer const&>(object);
  376. auto& buffer = array_buffer.buffer();
  377. auto byte_length = array_buffer.byte_length();
  378. print_type("ArrayBuffer");
  379. js_out("\n byteLength: ");
  380. print_value(JS::Value((double)byte_length), seen_objects);
  381. if (!byte_length)
  382. return;
  383. js_outln();
  384. for (size_t i = 0; i < byte_length; ++i) {
  385. js_out("{:02x}", buffer[i]);
  386. if (i + 1 < byte_length) {
  387. if ((i + 1) % 32 == 0)
  388. js_outln();
  389. else if ((i + 1) % 16 == 0)
  390. js_out(" ");
  391. else
  392. js_out(" ");
  393. }
  394. }
  395. }
  396. static void print_shadow_realm(JS::Object const&, HashTable<JS::Object*>&)
  397. {
  398. // Not much we can show here that would be useful. Realm pointer address?!
  399. print_type("ShadowRealm");
  400. }
  401. template<typename T>
  402. static void print_number(T number) requires IsArithmetic<T>
  403. {
  404. js_out("\033[35;1m");
  405. js_out("{}", number);
  406. js_out("\033[0m");
  407. }
  408. static void print_typed_array(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  409. {
  410. auto& typed_array_base = static_cast<JS::TypedArrayBase const&>(object);
  411. auto& array_buffer = *typed_array_base.viewed_array_buffer();
  412. auto length = typed_array_base.array_length();
  413. print_type(object.class_name());
  414. js_out("\n length: ");
  415. print_value(JS::Value(length), seen_objects);
  416. js_out("\n byteLength: ");
  417. print_value(JS::Value(typed_array_base.byte_length()), seen_objects);
  418. js_out("\n buffer: ");
  419. print_type("ArrayBuffer");
  420. if (array_buffer.is_detached())
  421. js_out(" (detached)");
  422. js_out(" @ {:p}", &array_buffer);
  423. if (!length || array_buffer.is_detached())
  424. return;
  425. js_outln();
  426. // FIXME: This kinda sucks.
  427. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  428. if (is<JS::ClassName>(object)) { \
  429. js_out("[ "); \
  430. auto& typed_array = static_cast<JS::ClassName const&>(typed_array_base); \
  431. auto data = typed_array.data(); \
  432. for (size_t i = 0; i < length; ++i) { \
  433. if (i > 0) \
  434. js_out(", "); \
  435. print_number(data[i]); \
  436. } \
  437. js_out(" ]"); \
  438. return; \
  439. }
  440. JS_ENUMERATE_TYPED_ARRAYS
  441. #undef __JS_ENUMERATE
  442. VERIFY_NOT_REACHED();
  443. }
  444. static void print_data_view(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  445. {
  446. auto& data_view = static_cast<JS::DataView const&>(object);
  447. print_type("DataView");
  448. js_out("\n byteLength: ");
  449. print_value(JS::Value(data_view.byte_length()), seen_objects);
  450. js_out("\n byteOffset: ");
  451. print_value(JS::Value(data_view.byte_offset()), seen_objects);
  452. js_out("\n buffer: ");
  453. print_type("ArrayBuffer");
  454. js_out(" @ {:p}", data_view.viewed_array_buffer());
  455. }
  456. static void print_temporal_calendar(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  457. {
  458. auto& calendar = static_cast<JS::Temporal::Calendar const&>(object);
  459. print_type("Temporal.Calendar");
  460. js_out(" ");
  461. print_value(JS::js_string(object.vm(), calendar.identifier()), seen_objects);
  462. }
  463. static void print_temporal_duration(JS::Object const& object, HashTable<JS::Object*>&)
  464. {
  465. auto& duration = static_cast<JS::Temporal::Duration const&>(object);
  466. print_type("Temporal.Duration");
  467. 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());
  468. }
  469. static void print_temporal_instant(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  470. {
  471. auto& instant = static_cast<JS::Temporal::Instant const&>(object);
  472. print_type("Temporal.Instant");
  473. js_out(" ");
  474. // FIXME: Print human readable date and time, like in print_date() - ideally handling arbitrarily large values since we get a bigint.
  475. print_value(&instant.nanoseconds(), seen_objects);
  476. }
  477. static void print_temporal_plain_date(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  478. {
  479. auto& plain_date = static_cast<JS::Temporal::PlainDate const&>(object);
  480. print_type("Temporal.PlainDate");
  481. js_out(" \033[34;1m{:04}-{:02}-{:02}\033[0m", plain_date.iso_year(), plain_date.iso_month(), plain_date.iso_day());
  482. js_out("\n calendar: ");
  483. print_value(&plain_date.calendar(), seen_objects);
  484. }
  485. static void print_temporal_plain_date_time(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  486. {
  487. auto& plain_date_time = static_cast<JS::Temporal::PlainDateTime const&>(object);
  488. print_type("Temporal.PlainDateTime");
  489. 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());
  490. js_out("\n calendar: ");
  491. print_value(&plain_date_time.calendar(), seen_objects);
  492. }
  493. static void print_temporal_plain_month_day(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  494. {
  495. auto& plain_month_day = static_cast<JS::Temporal::PlainMonthDay const&>(object);
  496. print_type("Temporal.PlainMonthDay");
  497. // Also has an [[ISOYear]] internal slot, but showing that here seems rather unexpected.
  498. js_out(" \033[34;1m{:02}-{:02}\033[0m", plain_month_day.iso_month(), plain_month_day.iso_day());
  499. js_out("\n calendar: ");
  500. print_value(&plain_month_day.calendar(), seen_objects);
  501. }
  502. static void print_temporal_plain_time(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  503. {
  504. auto& plain_time = static_cast<JS::Temporal::PlainTime const&>(object);
  505. print_type("Temporal.PlainTime");
  506. 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());
  507. js_out("\n calendar: ");
  508. print_value(&plain_time.calendar(), seen_objects);
  509. }
  510. static void print_temporal_plain_year_month(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  511. {
  512. auto& plain_year_month = static_cast<JS::Temporal::PlainYearMonth const&>(object);
  513. print_type("Temporal.PlainYearMonth");
  514. // Also has an [[ISODay]] internal slot, but showing that here seems rather unexpected.
  515. js_out(" \033[34;1m{:04}-{:02}\033[0m", plain_year_month.iso_year(), plain_year_month.iso_month());
  516. js_out("\n calendar: ");
  517. print_value(&plain_year_month.calendar(), seen_objects);
  518. }
  519. static void print_temporal_time_zone(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  520. {
  521. auto& time_zone = static_cast<JS::Temporal::TimeZone const&>(object);
  522. print_type("Temporal.TimeZone");
  523. js_out(" ");
  524. print_value(JS::js_string(object.vm(), time_zone.identifier()), seen_objects);
  525. if (time_zone.offset_nanoseconds().has_value()) {
  526. js_out("\n offset (ns): ");
  527. print_value(JS::Value(*time_zone.offset_nanoseconds()), seen_objects);
  528. }
  529. }
  530. static void print_temporal_zoned_date_time(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  531. {
  532. auto& zoned_date_time = static_cast<JS::Temporal::ZonedDateTime const&>(object);
  533. print_type("Temporal.ZonedDateTime");
  534. js_out("\n epochNanoseconds: ");
  535. print_value(&zoned_date_time.nanoseconds(), seen_objects);
  536. js_out("\n timeZone: ");
  537. print_value(&zoned_date_time.time_zone(), seen_objects);
  538. js_out("\n calendar: ");
  539. print_value(&zoned_date_time.calendar(), seen_objects);
  540. }
  541. static void print_intl_display_names(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  542. {
  543. auto& display_names = static_cast<JS::Intl::DisplayNames const&>(object);
  544. print_type("Intl.DisplayNames");
  545. js_out("\n locale: ");
  546. print_value(js_string(object.vm(), display_names.locale()), seen_objects);
  547. js_out("\n type: ");
  548. print_value(js_string(object.vm(), display_names.type_string()), seen_objects);
  549. js_out("\n style: ");
  550. print_value(js_string(object.vm(), display_names.style_string()), seen_objects);
  551. js_out("\n fallback: ");
  552. print_value(js_string(object.vm(), display_names.fallback_string()), seen_objects);
  553. if (display_names.has_language_display()) {
  554. js_out("\n languageDisplay: ");
  555. print_value(js_string(object.vm(), display_names.language_display_string()), seen_objects);
  556. }
  557. }
  558. static void print_intl_locale(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  559. {
  560. auto& locale = static_cast<JS::Intl::Locale const&>(object);
  561. print_type("Intl.Locale");
  562. js_out("\n locale: ");
  563. print_value(js_string(object.vm(), locale.locale()), seen_objects);
  564. if (locale.has_calendar()) {
  565. js_out("\n calendar: ");
  566. print_value(js_string(object.vm(), locale.calendar()), seen_objects);
  567. }
  568. if (locale.has_case_first()) {
  569. js_out("\n caseFirst: ");
  570. print_value(js_string(object.vm(), locale.case_first()), seen_objects);
  571. }
  572. if (locale.has_collation()) {
  573. js_out("\n collation: ");
  574. print_value(js_string(object.vm(), locale.collation()), seen_objects);
  575. }
  576. if (locale.has_hour_cycle()) {
  577. js_out("\n hourCycle: ");
  578. print_value(js_string(object.vm(), locale.hour_cycle()), seen_objects);
  579. }
  580. if (locale.has_numbering_system()) {
  581. js_out("\n numberingSystem: ");
  582. print_value(js_string(object.vm(), locale.numbering_system()), seen_objects);
  583. }
  584. js_out("\n numeric: ");
  585. print_value(JS::Value(locale.numeric()), seen_objects);
  586. }
  587. static void print_intl_list_format(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  588. {
  589. auto& list_format = static_cast<JS::Intl::ListFormat const&>(object);
  590. print_type("Intl.ListFormat");
  591. js_out("\n locale: ");
  592. print_value(js_string(object.vm(), list_format.locale()), seen_objects);
  593. js_out("\n type: ");
  594. print_value(js_string(object.vm(), list_format.type_string()), seen_objects);
  595. js_out("\n style: ");
  596. print_value(js_string(object.vm(), list_format.style_string()), seen_objects);
  597. }
  598. static void print_intl_number_format(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  599. {
  600. auto& number_format = static_cast<JS::Intl::NumberFormat const&>(object);
  601. print_type("Intl.NumberFormat");
  602. js_out("\n locale: ");
  603. print_value(js_string(object.vm(), number_format.locale()), seen_objects);
  604. js_out("\n dataLocale: ");
  605. print_value(js_string(object.vm(), number_format.data_locale()), seen_objects);
  606. js_out("\n numberingSystem: ");
  607. print_value(js_string(object.vm(), number_format.numbering_system()), seen_objects);
  608. js_out("\n style: ");
  609. print_value(js_string(object.vm(), number_format.style_string()), seen_objects);
  610. if (number_format.has_currency()) {
  611. js_out("\n currency: ");
  612. print_value(js_string(object.vm(), number_format.currency()), seen_objects);
  613. }
  614. if (number_format.has_currency_display()) {
  615. js_out("\n currencyDisplay: ");
  616. print_value(js_string(object.vm(), number_format.currency_display_string()), seen_objects);
  617. }
  618. if (number_format.has_currency_sign()) {
  619. js_out("\n currencySign: ");
  620. print_value(js_string(object.vm(), number_format.currency_sign_string()), seen_objects);
  621. }
  622. if (number_format.has_unit()) {
  623. js_out("\n unit: ");
  624. print_value(js_string(object.vm(), number_format.unit()), seen_objects);
  625. }
  626. if (number_format.has_unit_display()) {
  627. js_out("\n unitDisplay: ");
  628. print_value(js_string(object.vm(), number_format.unit_display_string()), seen_objects);
  629. }
  630. js_out("\n minimumIntegerDigits: ");
  631. print_value(JS::Value(number_format.min_integer_digits()), seen_objects);
  632. if (number_format.has_min_fraction_digits()) {
  633. js_out("\n minimumFractionDigits: ");
  634. print_value(JS::Value(number_format.min_fraction_digits()), seen_objects);
  635. }
  636. if (number_format.has_max_fraction_digits()) {
  637. js_out("\n maximumFractionDigits: ");
  638. print_value(JS::Value(number_format.max_fraction_digits()), seen_objects);
  639. }
  640. if (number_format.has_min_significant_digits()) {
  641. js_out("\n minimumSignificantDigits: ");
  642. print_value(JS::Value(number_format.min_significant_digits()), seen_objects);
  643. }
  644. if (number_format.has_max_significant_digits()) {
  645. js_out("\n maximumSignificantDigits: ");
  646. print_value(JS::Value(number_format.max_significant_digits()), seen_objects);
  647. }
  648. js_out("\n useGrouping: ");
  649. print_value(JS::Value(number_format.use_grouping()), seen_objects);
  650. js_out("\n roundingType: ");
  651. print_value(js_string(object.vm(), number_format.rounding_type_string()), seen_objects);
  652. js_out("\n notation: ");
  653. print_value(js_string(object.vm(), number_format.notation_string()), seen_objects);
  654. if (number_format.has_compact_display()) {
  655. js_out("\n compactDisplay: ");
  656. print_value(js_string(object.vm(), number_format.compact_display_string()), seen_objects);
  657. }
  658. js_out("\n signDisplay: ");
  659. print_value(js_string(object.vm(), number_format.sign_display_string()), seen_objects);
  660. }
  661. static void print_intl_date_time_format(JS::Object& object, HashTable<JS::Object*>& seen_objects)
  662. {
  663. auto& date_time_format = static_cast<JS::Intl::DateTimeFormat&>(object);
  664. print_type("Intl.DateTimeFormat");
  665. js_out("\n locale: ");
  666. print_value(js_string(object.vm(), date_time_format.locale()), seen_objects);
  667. js_out("\n pattern: ");
  668. print_value(js_string(object.vm(), date_time_format.pattern()), seen_objects);
  669. js_out("\n calendar: ");
  670. print_value(js_string(object.vm(), date_time_format.calendar()), seen_objects);
  671. js_out("\n numberingSystem: ");
  672. print_value(js_string(object.vm(), date_time_format.numbering_system()), seen_objects);
  673. if (date_time_format.has_hour_cycle()) {
  674. js_out("\n hourCycle: ");
  675. print_value(js_string(object.vm(), date_time_format.hour_cycle_string()), seen_objects);
  676. }
  677. js_out("\n timeZone: ");
  678. print_value(js_string(object.vm(), date_time_format.time_zone()), seen_objects);
  679. if (date_time_format.has_date_style()) {
  680. js_out("\n dateStyle: ");
  681. print_value(js_string(object.vm(), date_time_format.date_style_string()), seen_objects);
  682. }
  683. if (date_time_format.has_time_style()) {
  684. js_out("\n timeStyle: ");
  685. print_value(js_string(object.vm(), date_time_format.time_style_string()), seen_objects);
  686. }
  687. JS::Intl::for_each_calendar_field(date_time_format.global_object(), date_time_format, [&](auto& option, auto const& property, auto const&) -> JS::ThrowCompletionOr<void> {
  688. using ValueType = typename RemoveReference<decltype(option)>::ValueType;
  689. if (!option.has_value())
  690. return {};
  691. js_out("\n {}: ", property);
  692. if constexpr (IsIntegral<ValueType>) {
  693. print_value(JS::Value(*option), seen_objects);
  694. } else {
  695. auto name = Unicode::calendar_pattern_style_to_string(*option);
  696. print_value(js_string(object.vm(), name), seen_objects);
  697. }
  698. return {};
  699. });
  700. }
  701. static void print_intl_relative_time_format(JS::Object& object, HashTable<JS::Object*>& seen_objects)
  702. {
  703. auto& date_time_format = static_cast<JS::Intl::RelativeTimeFormat&>(object);
  704. print_type("Intl.RelativeTimeFormat");
  705. js_out("\n locale: ");
  706. print_value(js_string(object.vm(), date_time_format.locale()), seen_objects);
  707. js_out("\n numberingSystem: ");
  708. print_value(js_string(object.vm(), date_time_format.numbering_system()), seen_objects);
  709. js_out("\n style: ");
  710. print_value(js_string(object.vm(), date_time_format.style_string()), seen_objects);
  711. js_out("\n numeric: ");
  712. print_value(js_string(object.vm(), date_time_format.numeric_string()), seen_objects);
  713. }
  714. static void print_intl_plural_rules(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  715. {
  716. auto& plural_rules = static_cast<JS::Intl::PluralRules const&>(object);
  717. print_type("Intl.PluralRules");
  718. js_out("\n locale: ");
  719. print_value(js_string(object.vm(), plural_rules.locale()), seen_objects);
  720. js_out("\n type: ");
  721. print_value(js_string(object.vm(), plural_rules.type_string()), seen_objects);
  722. js_out("\n minimumIntegerDigits: ");
  723. print_value(JS::Value(plural_rules.min_integer_digits()), seen_objects);
  724. if (plural_rules.has_min_fraction_digits()) {
  725. js_out("\n minimumFractionDigits: ");
  726. print_value(JS::Value(plural_rules.min_fraction_digits()), seen_objects);
  727. }
  728. if (plural_rules.has_max_fraction_digits()) {
  729. js_out("\n maximumFractionDigits: ");
  730. print_value(JS::Value(plural_rules.max_fraction_digits()), seen_objects);
  731. }
  732. if (plural_rules.has_min_significant_digits()) {
  733. js_out("\n minimumSignificantDigits: ");
  734. print_value(JS::Value(plural_rules.min_significant_digits()), seen_objects);
  735. }
  736. if (plural_rules.has_max_significant_digits()) {
  737. js_out("\n maximumSignificantDigits: ");
  738. print_value(JS::Value(plural_rules.max_significant_digits()), seen_objects);
  739. }
  740. js_out("\n roundingType: ");
  741. print_value(js_string(object.vm(), plural_rules.rounding_type_string()), seen_objects);
  742. }
  743. static void print_intl_collator(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  744. {
  745. auto& collator = static_cast<JS::Intl::Collator const&>(object);
  746. print_type("Intl.Collator");
  747. out("\n locale: ");
  748. print_value(js_string(object.vm(), collator.locale()), seen_objects);
  749. out("\n usage: ");
  750. print_value(js_string(object.vm(), collator.usage_string()), seen_objects);
  751. out("\n sensitivity: ");
  752. print_value(js_string(object.vm(), collator.sensitivity_string()), seen_objects);
  753. out("\n caseFirst: ");
  754. print_value(js_string(object.vm(), collator.case_first_string()), seen_objects);
  755. out("\n collation: ");
  756. print_value(js_string(object.vm(), collator.collation()), seen_objects);
  757. out("\n ignorePunctuation: ");
  758. print_value(JS::Value(collator.ignore_punctuation()), seen_objects);
  759. out("\n numeric: ");
  760. print_value(JS::Value(collator.numeric()), seen_objects);
  761. }
  762. static void print_intl_segmenter(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  763. {
  764. auto& segmenter = static_cast<JS::Intl::Segmenter const&>(object);
  765. print_type("Intl.Segmenter");
  766. out("\n locale: ");
  767. print_value(js_string(object.vm(), segmenter.locale()), seen_objects);
  768. out("\n granularity: ");
  769. print_value(js_string(object.vm(), segmenter.segmenter_granularity_string()), seen_objects);
  770. }
  771. static void print_intl_segments(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  772. {
  773. auto& segments = static_cast<JS::Intl::Segments const&>(object);
  774. print_type("Segments");
  775. out("\n string: ");
  776. print_value(js_string(object.vm(), segments.segments_string()), seen_objects);
  777. out("\n segmenter: ");
  778. print_value(&segments.segments_segmenter(), seen_objects);
  779. }
  780. static void print_primitive_wrapper_object(FlyString const& name, JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  781. {
  782. // BooleanObject, NumberObject, StringObject
  783. print_type(name);
  784. js_out(" ");
  785. print_value(&object, seen_objects);
  786. }
  787. static void print_value(JS::Value value, HashTable<JS::Object*>& seen_objects)
  788. {
  789. if (value.is_empty()) {
  790. js_out("\033[34;1m<empty>\033[0m");
  791. return;
  792. }
  793. if (value.is_object()) {
  794. if (seen_objects.contains(&value.as_object())) {
  795. // FIXME: Maybe we should only do this for circular references,
  796. // not for all reoccurring objects.
  797. js_out("<already printed Object {}>", &value.as_object());
  798. return;
  799. }
  800. seen_objects.set(&value.as_object());
  801. }
  802. if (value.is_object()) {
  803. auto& object = value.as_object();
  804. if (is<JS::Array>(object))
  805. return print_array(static_cast<JS::Array&>(object), seen_objects);
  806. if (object.is_function())
  807. return print_function(object, seen_objects);
  808. if (is<JS::Date>(object))
  809. return print_date(object, seen_objects);
  810. if (is<JS::Error>(object))
  811. return print_error(object, seen_objects);
  812. auto prototype_or_error = object.internal_get_prototype_of();
  813. if (prototype_or_error.has_value() && prototype_or_error.value() == object.global_object().error_prototype())
  814. return print_error(object, seen_objects);
  815. if (is<JS::RegExpObject>(object))
  816. return print_regexp_object(object, seen_objects);
  817. if (is<JS::Map>(object))
  818. return print_map(object, seen_objects);
  819. if (is<JS::Set>(object))
  820. return print_set(object, seen_objects);
  821. if (is<JS::DataView>(object))
  822. return print_data_view(object, seen_objects);
  823. if (is<JS::ProxyObject>(object))
  824. return print_proxy_object(object, seen_objects);
  825. if (is<JS::Promise>(object))
  826. return print_promise(object, seen_objects);
  827. if (is<JS::ArrayBuffer>(object))
  828. return print_array_buffer(object, seen_objects);
  829. if (is<JS::ShadowRealm>(object))
  830. return print_shadow_realm(object, seen_objects);
  831. if (object.is_typed_array())
  832. return print_typed_array(object, seen_objects);
  833. if (is<JS::StringObject>(object))
  834. return print_primitive_wrapper_object("String", object, seen_objects);
  835. if (is<JS::NumberObject>(object))
  836. return print_primitive_wrapper_object("Number", object, seen_objects);
  837. if (is<JS::BooleanObject>(object))
  838. return print_primitive_wrapper_object("Boolean", object, seen_objects);
  839. if (is<JS::Temporal::Calendar>(object))
  840. return print_temporal_calendar(object, seen_objects);
  841. if (is<JS::Temporal::Duration>(object))
  842. return print_temporal_duration(object, seen_objects);
  843. if (is<JS::Temporal::Instant>(object))
  844. return print_temporal_instant(object, seen_objects);
  845. if (is<JS::Temporal::PlainDate>(object))
  846. return print_temporal_plain_date(object, seen_objects);
  847. if (is<JS::Temporal::PlainDateTime>(object))
  848. return print_temporal_plain_date_time(object, seen_objects);
  849. if (is<JS::Temporal::PlainMonthDay>(object))
  850. return print_temporal_plain_month_day(object, seen_objects);
  851. if (is<JS::Temporal::PlainTime>(object))
  852. return print_temporal_plain_time(object, seen_objects);
  853. if (is<JS::Temporal::PlainYearMonth>(object))
  854. return print_temporal_plain_year_month(object, seen_objects);
  855. if (is<JS::Temporal::TimeZone>(object))
  856. return print_temporal_time_zone(object, seen_objects);
  857. if (is<JS::Temporal::ZonedDateTime>(object))
  858. return print_temporal_zoned_date_time(object, seen_objects);
  859. if (is<JS::Intl::DisplayNames>(object))
  860. return print_intl_display_names(object, seen_objects);
  861. if (is<JS::Intl::Locale>(object))
  862. return print_intl_locale(object, seen_objects);
  863. if (is<JS::Intl::ListFormat>(object))
  864. return print_intl_list_format(object, seen_objects);
  865. if (is<JS::Intl::NumberFormat>(object))
  866. return print_intl_number_format(object, seen_objects);
  867. if (is<JS::Intl::DateTimeFormat>(object))
  868. return print_intl_date_time_format(object, seen_objects);
  869. if (is<JS::Intl::RelativeTimeFormat>(object))
  870. return print_intl_relative_time_format(object, seen_objects);
  871. if (is<JS::Intl::PluralRules>(object))
  872. return print_intl_plural_rules(object, seen_objects);
  873. if (is<JS::Intl::Collator>(object))
  874. return print_intl_collator(object, seen_objects);
  875. if (is<JS::Intl::Segmenter>(object))
  876. return print_intl_segmenter(object, seen_objects);
  877. if (is<JS::Intl::Segments>(object))
  878. return print_intl_segments(object, seen_objects);
  879. return print_object(object, seen_objects);
  880. }
  881. if (value.is_string())
  882. js_out("\033[32;1m");
  883. else if (value.is_number() || value.is_bigint())
  884. js_out("\033[35;1m");
  885. else if (value.is_boolean())
  886. js_out("\033[33;1m");
  887. else if (value.is_null())
  888. js_out("\033[33;1m");
  889. else if (value.is_undefined())
  890. js_out("\033[34;1m");
  891. if (value.is_string())
  892. js_out("\"");
  893. else if (value.is_negative_zero())
  894. js_out("-");
  895. js_out("{}", value.to_string_without_side_effects());
  896. if (value.is_string())
  897. js_out("\"");
  898. js_out("\033[0m");
  899. }
  900. static void print(JS::Value value)
  901. {
  902. HashTable<JS::Object*> seen_objects;
  903. print_value(value, seen_objects);
  904. js_outln();
  905. }
  906. static bool write_to_file(String const& path)
  907. {
  908. int fd = open(path.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  909. for (size_t i = 0; i < repl_statements.size(); i++) {
  910. auto line = repl_statements[i];
  911. if (line.length() && i != repl_statements.size() - 1) {
  912. ssize_t nwritten = write(fd, line.characters(), line.length());
  913. if (nwritten < 0) {
  914. close(fd);
  915. return false;
  916. }
  917. }
  918. if (i != repl_statements.size() - 1) {
  919. char ch = '\n';
  920. ssize_t nwritten = write(fd, &ch, 1);
  921. if (nwritten != 1) {
  922. perror("write");
  923. close(fd);
  924. return false;
  925. }
  926. }
  927. }
  928. close(fd);
  929. return true;
  930. }
  931. static bool parse_and_run(JS::Interpreter& interpreter, StringView source, StringView source_name)
  932. {
  933. enum class ReturnEarly {
  934. No,
  935. Yes,
  936. };
  937. JS::ThrowCompletionOr<JS::Value> result { JS::js_undefined() };
  938. auto run_script_or_module = [&](auto& script_or_module) {
  939. if (s_dump_ast)
  940. script_or_module->parse_node().dump(0);
  941. if (JS::Bytecode::g_dump_bytecode || s_run_bytecode) {
  942. auto executable = JS::Bytecode::Generator::generate(script_or_module->parse_node());
  943. executable->name = source_name;
  944. if (s_opt_bytecode) {
  945. auto& passes = JS::Bytecode::Interpreter::optimization_pipeline();
  946. passes.perform(*executable);
  947. dbgln("Optimisation passes took {}us", passes.elapsed());
  948. }
  949. if (JS::Bytecode::g_dump_bytecode)
  950. executable->dump();
  951. if (s_run_bytecode) {
  952. JS::Bytecode::Interpreter bytecode_interpreter(interpreter.global_object(), interpreter.realm());
  953. result = bytecode_interpreter.run(*executable);
  954. } else {
  955. return ReturnEarly::Yes;
  956. }
  957. } else {
  958. result = interpreter.run(*script_or_module);
  959. }
  960. return ReturnEarly::No;
  961. };
  962. if (!s_as_module) {
  963. auto script_or_error = JS::Script::parse(source, interpreter.realm(), source_name);
  964. if (script_or_error.is_error()) {
  965. auto error = script_or_error.error()[0];
  966. auto hint = error.source_location_hint(source);
  967. if (!hint.is_empty())
  968. outln("{}", hint);
  969. outln(error.to_string());
  970. result = JS::SyntaxError::create(interpreter.global_object(), error.to_string());
  971. } else {
  972. auto return_early = run_script_or_module(script_or_error.value());
  973. if (return_early == ReturnEarly::Yes)
  974. return true;
  975. }
  976. } else {
  977. auto module_or_error = JS::SourceTextModule::parse(source, interpreter.realm(), source_name);
  978. if (module_or_error.is_error()) {
  979. auto error = module_or_error.error()[0];
  980. auto hint = error.source_location_hint(source);
  981. if (!hint.is_empty())
  982. outln("{}", hint);
  983. outln(error.to_string());
  984. result = JS::SyntaxError::create(interpreter.global_object(), error.to_string());
  985. } else {
  986. auto return_early = run_script_or_module(module_or_error.value());
  987. if (return_early == ReturnEarly::Yes)
  988. return true;
  989. }
  990. }
  991. auto handle_exception = [&](JS::Value thrown_value) {
  992. js_out("Uncaught exception: ");
  993. print(thrown_value);
  994. if (!thrown_value.is_object() || !is<JS::Error>(thrown_value.as_object()))
  995. return;
  996. auto& traceback = static_cast<JS::Error const&>(thrown_value.as_object()).traceback();
  997. if (traceback.size() > 1) {
  998. unsigned repetitions = 0;
  999. for (size_t i = 0; i < traceback.size(); ++i) {
  1000. auto& traceback_frame = traceback[i];
  1001. if (i + 1 < traceback.size()) {
  1002. auto& next_traceback_frame = traceback[i + 1];
  1003. if (next_traceback_frame.function_name == traceback_frame.function_name) {
  1004. repetitions++;
  1005. continue;
  1006. }
  1007. }
  1008. if (repetitions > 4) {
  1009. // If more than 5 (1 + >4) consecutive function calls with the same name, print
  1010. // the name only once and show the number of repetitions instead. This prevents
  1011. // printing ridiculously large call stacks of recursive functions.
  1012. js_outln(" -> {}", traceback_frame.function_name);
  1013. js_outln(" {} more calls", repetitions);
  1014. } else {
  1015. for (size_t j = 0; j < repetitions + 1; ++j)
  1016. js_outln(" -> {}", traceback_frame.function_name);
  1017. }
  1018. repetitions = 0;
  1019. }
  1020. }
  1021. };
  1022. if (!result.is_error())
  1023. last_value = JS::make_handle(result.value());
  1024. if (result.is_error()) {
  1025. VERIFY(result.throw_completion().value().has_value());
  1026. handle_exception(*result.release_error().value());
  1027. return false;
  1028. } else if (s_print_last_result) {
  1029. print(result.value());
  1030. }
  1031. return true;
  1032. }
  1033. static JS::ThrowCompletionOr<JS::Value> load_file_impl(JS::VM& vm, JS::GlobalObject& global_object)
  1034. {
  1035. auto filename = TRY(vm.argument(0).to_string(global_object));
  1036. auto file = Core::File::construct(filename);
  1037. if (!file->open(Core::OpenMode::ReadOnly))
  1038. return vm.throw_completion<JS::Error>(global_object, String::formatted("Failed to open '{}': {}", filename, file->error_string()));
  1039. auto file_contents = file->read_all();
  1040. auto source = StringView { file_contents };
  1041. auto script_or_error = JS::Script::parse(source, vm.interpreter().realm(), filename);
  1042. if (script_or_error.is_error()) {
  1043. auto& error = script_or_error.error()[0];
  1044. return vm.throw_completion<JS::SyntaxError>(global_object, error.to_string());
  1045. }
  1046. // FIXME: Use eval()-like semantics and execute in current scope?
  1047. TRY(vm.interpreter().run(script_or_error.value()));
  1048. return JS::js_undefined();
  1049. }
  1050. static JS::ThrowCompletionOr<JS::Value> load_json_impl(JS::VM& vm, JS::GlobalObject& global_object)
  1051. {
  1052. auto filename = TRY(vm.argument(0).to_string(global_object));
  1053. auto file = Core::File::construct(filename);
  1054. if (!file->open(Core::OpenMode::ReadOnly))
  1055. return vm.throw_completion<JS::Error>(global_object, String::formatted("Failed to open '{}': {}", filename, file->error_string()));
  1056. auto file_contents = file->read_all();
  1057. auto json = JsonValue::from_string(file_contents);
  1058. if (json.is_error())
  1059. return vm.throw_completion<JS::SyntaxError>(global_object, JS::ErrorType::JsonMalformed);
  1060. return JS::JSONObject::parse_json_value(global_object, json.value());
  1061. }
  1062. void ReplObject::initialize_global_object()
  1063. {
  1064. Base::initialize_global_object();
  1065. define_direct_property("global", this, JS::Attribute::Enumerable);
  1066. u8 attr = JS::Attribute::Configurable | JS::Attribute::Writable | JS::Attribute::Enumerable;
  1067. define_native_function("exit", exit_interpreter, 0, attr);
  1068. define_native_function("help", repl_help, 0, attr);
  1069. define_native_function("load", load_file, 1, attr);
  1070. define_native_function("save", save_to_file, 1, attr);
  1071. define_native_function("loadJSON", load_json, 1, attr);
  1072. define_native_accessor(
  1073. "_",
  1074. [](JS::VM&, JS::GlobalObject&) {
  1075. return last_value.value();
  1076. },
  1077. [](JS::VM& vm, JS::GlobalObject& global_object) -> JS::ThrowCompletionOr<JS::Value> {
  1078. VERIFY(is<ReplObject>(global_object));
  1079. outln("Disable writing last value to '_'");
  1080. // We must delete first otherwise this setter gets called recursively.
  1081. TRY(global_object.internal_delete(JS::PropertyKey { "_" }));
  1082. auto value = vm.argument(0);
  1083. TRY(global_object.internal_set(JS::PropertyKey { "_" }, value, &global_object));
  1084. return value;
  1085. },
  1086. attr);
  1087. }
  1088. JS_DEFINE_NATIVE_FUNCTION(ReplObject::save_to_file)
  1089. {
  1090. if (!vm.argument_count())
  1091. return JS::Value(false);
  1092. String save_path = vm.argument(0).to_string_without_side_effects();
  1093. StringView path = StringView(save_path.characters());
  1094. if (write_to_file(path)) {
  1095. return JS::Value(true);
  1096. }
  1097. return JS::Value(false);
  1098. }
  1099. JS_DEFINE_NATIVE_FUNCTION(ReplObject::exit_interpreter)
  1100. {
  1101. if (!vm.argument_count())
  1102. exit(0);
  1103. exit(TRY(vm.argument(0).to_number(global_object)).as_double());
  1104. }
  1105. JS_DEFINE_NATIVE_FUNCTION(ReplObject::repl_help)
  1106. {
  1107. js_outln("REPL commands:");
  1108. js_outln(" exit(code): exit the REPL with specified code. Defaults to 0.");
  1109. js_outln(" help(): display this menu");
  1110. js_outln(" load(file): load given JS file into running session. For example: load(\"foo.js\")");
  1111. js_outln(" save(file): write REPL input history to the given file. For example: save(\"foo.txt\")");
  1112. return JS::js_undefined();
  1113. }
  1114. JS_DEFINE_NATIVE_FUNCTION(ReplObject::load_file)
  1115. {
  1116. return load_file_impl(vm, global_object);
  1117. }
  1118. JS_DEFINE_NATIVE_FUNCTION(ReplObject::load_json)
  1119. {
  1120. return load_json_impl(vm, global_object);
  1121. }
  1122. void ScriptObject::initialize_global_object()
  1123. {
  1124. Base::initialize_global_object();
  1125. define_direct_property("global", this, JS::Attribute::Enumerable);
  1126. u8 attr = JS::Attribute::Configurable | JS::Attribute::Writable | JS::Attribute::Enumerable;
  1127. define_native_function("load", load_file, 1, attr);
  1128. define_native_function("loadJSON", load_json, 1, attr);
  1129. }
  1130. JS_DEFINE_NATIVE_FUNCTION(ScriptObject::load_file)
  1131. {
  1132. return load_file_impl(vm, global_object);
  1133. }
  1134. JS_DEFINE_NATIVE_FUNCTION(ScriptObject::load_json)
  1135. {
  1136. return load_json_impl(vm, global_object);
  1137. }
  1138. static void repl(JS::Interpreter& interpreter)
  1139. {
  1140. while (!s_fail_repl) {
  1141. String piece = read_next_piece();
  1142. if (piece.is_empty())
  1143. continue;
  1144. repl_statements.append(piece);
  1145. parse_and_run(interpreter, piece, "REPL");
  1146. }
  1147. }
  1148. static Function<void()> interrupt_interpreter;
  1149. static void sigint_handler()
  1150. {
  1151. interrupt_interpreter();
  1152. }
  1153. class ReplConsoleClient final : public JS::ConsoleClient {
  1154. public:
  1155. ReplConsoleClient(JS::Console& console)
  1156. : ConsoleClient(console)
  1157. {
  1158. }
  1159. virtual void clear() override
  1160. {
  1161. js_out("\033[3J\033[H\033[2J");
  1162. m_group_stack_depth = 0;
  1163. fflush(stdout);
  1164. }
  1165. virtual void end_group() override
  1166. {
  1167. if (m_group_stack_depth > 0)
  1168. m_group_stack_depth--;
  1169. }
  1170. // 2.3. Printer(logLevel, args[, options]), https://console.spec.whatwg.org/#printer
  1171. virtual JS::ThrowCompletionOr<JS::Value> printer(JS::Console::LogLevel log_level, PrinterArguments arguments) override
  1172. {
  1173. String indent = String::repeated(" ", m_group_stack_depth);
  1174. if (log_level == JS::Console::LogLevel::Trace) {
  1175. auto trace = arguments.get<JS::Console::Trace>();
  1176. StringBuilder builder;
  1177. if (!trace.label.is_empty())
  1178. builder.appendff("{}\033[36;1m{}\033[0m\n", indent, trace.label);
  1179. for (auto& function_name : trace.stack)
  1180. builder.appendff("{}-> {}\n", indent, function_name);
  1181. js_outln("{}", builder.string_view());
  1182. return JS::js_undefined();
  1183. }
  1184. if (log_level == JS::Console::LogLevel::Group || log_level == JS::Console::LogLevel::GroupCollapsed) {
  1185. auto group = arguments.get<JS::Console::Group>();
  1186. js_outln("{}\033[36;1m{}\033[0m", indent, group.label);
  1187. m_group_stack_depth++;
  1188. return JS::js_undefined();
  1189. }
  1190. auto output = String::join(" ", arguments.get<Vector<JS::Value>>());
  1191. m_console.output_debug_message(log_level, output);
  1192. switch (log_level) {
  1193. case JS::Console::LogLevel::Debug:
  1194. js_outln("{}\033[36;1m{}\033[0m", indent, output);
  1195. break;
  1196. case JS::Console::LogLevel::Error:
  1197. case JS::Console::LogLevel::Assert:
  1198. js_outln("{}\033[31;1m{}\033[0m", indent, output);
  1199. break;
  1200. case JS::Console::LogLevel::Info:
  1201. js_outln("{}(i) {}", indent, output);
  1202. break;
  1203. case JS::Console::LogLevel::Log:
  1204. js_outln("{}{}", indent, output);
  1205. break;
  1206. case JS::Console::LogLevel::Warn:
  1207. case JS::Console::LogLevel::CountReset:
  1208. js_outln("{}\033[33;1m{}\033[0m", indent, output);
  1209. break;
  1210. default:
  1211. js_outln("{}{}", indent, output);
  1212. break;
  1213. }
  1214. return JS::js_undefined();
  1215. }
  1216. private:
  1217. int m_group_stack_depth { 0 };
  1218. };
  1219. ErrorOr<int> serenity_main(Main::Arguments arguments)
  1220. {
  1221. #ifdef __serenity__
  1222. TRY(Core::System::pledge("stdio rpath wpath cpath tty sigaction"));
  1223. #endif
  1224. bool gc_on_every_allocation = false;
  1225. bool disable_syntax_highlight = false;
  1226. StringView evaluate_script;
  1227. Vector<StringView> script_paths;
  1228. Core::ArgsParser args_parser;
  1229. args_parser.set_general_help("This is a JavaScript interpreter.");
  1230. args_parser.add_option(s_dump_ast, "Dump the AST", "dump-ast", 'A');
  1231. args_parser.add_option(JS::Bytecode::g_dump_bytecode, "Dump the bytecode", "dump-bytecode", 'd');
  1232. args_parser.add_option(s_run_bytecode, "Run the bytecode", "run-bytecode", 'b');
  1233. args_parser.add_option(s_opt_bytecode, "Optimize the bytecode", "optimize-bytecode", 'p');
  1234. args_parser.add_option(s_as_module, "Treat as module", "as-module", 'm');
  1235. args_parser.add_option(s_print_last_result, "Print last result", "print-last-result", 'l');
  1236. args_parser.add_option(s_strip_ansi, "Disable ANSI colors", "disable-ansi-colors", 'i');
  1237. args_parser.add_option(s_disable_source_location_hints, "Disable source location hints", "disable-source-location-hints", 'h');
  1238. args_parser.add_option(gc_on_every_allocation, "GC on every allocation", "gc-on-every-allocation", 'g');
  1239. args_parser.add_option(disable_syntax_highlight, "Disable live syntax highlighting", "no-syntax-highlight", 's');
  1240. args_parser.add_option(evaluate_script, "Evaluate argument as a script", "evaluate", 'c', "script");
  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 (evaluate_script.is_empty() && 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. StringBuilder builder;
  1466. StringView source_name;
  1467. if (evaluate_script.is_empty()) {
  1468. if (script_paths.size() > 1)
  1469. warnln("Warning: Multiple files supplied, this will concatenate the sources and resolve modules as if it was the first file");
  1470. for (auto& path : script_paths) {
  1471. auto file = TRY(Core::File::open(path, Core::OpenMode::ReadOnly));
  1472. auto file_contents = file->read_all();
  1473. auto source = StringView { file_contents };
  1474. builder.append(source);
  1475. }
  1476. source_name = script_paths[0];
  1477. } else {
  1478. builder.append(evaluate_script);
  1479. source_name = "eval"sv;
  1480. }
  1481. // We resolve modules as if it is the first file
  1482. if (!parse_and_run(*interpreter, builder.string_view(), source_name))
  1483. return 1;
  1484. }
  1485. return 0;
  1486. }