js.cpp 61 KB

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