js.cpp 42 KB

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