js.cpp 54 KB

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