js.cpp 66 KB

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