js.cpp 74 KB

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