js.cpp 56 KB

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