js.cpp 53 KB

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