js.cpp 35 KB

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