js.cpp 74 KB

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