js.cpp 66 KB

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