js.cpp 54 KB

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