js.cpp 35 KB

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