js.cpp 54 KB

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