js.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/ByteBuffer.h>
  27. #include <AK/NonnullOwnPtr.h>
  28. #include <AK/StringBuilder.h>
  29. #include <LibCore/ArgsParser.h>
  30. #include <LibCore/File.h>
  31. #include <LibJS/AST.h>
  32. #include <LibJS/Console.h>
  33. #include <LibJS/Interpreter.h>
  34. #include <LibJS/Parser.h>
  35. #include <LibJS/Runtime/Array.h>
  36. #include <LibJS/Runtime/Date.h>
  37. #include <LibJS/Runtime/Error.h>
  38. #include <LibJS/Runtime/Function.h>
  39. #include <LibJS/Runtime/GlobalObject.h>
  40. #include <LibJS/Runtime/Object.h>
  41. #include <LibJS/Runtime/PrimitiveString.h>
  42. #include <LibJS/Runtime/RegExpObject.h>
  43. #include <LibJS/Runtime/Shape.h>
  44. #include <LibJS/Runtime/Value.h>
  45. #include <LibLine/Editor.h>
  46. #include <signal.h>
  47. #include <stdio.h>
  48. RefPtr<JS::VM> vm;
  49. Vector<String> repl_statements;
  50. class ReplObject : public JS::GlobalObject {
  51. public:
  52. ReplObject();
  53. virtual void initialize() override;
  54. virtual ~ReplObject() override;
  55. private:
  56. virtual const char* class_name() const override { return "ReplObject"; }
  57. JS_DECLARE_NATIVE_FUNCTION(exit_interpreter);
  58. JS_DECLARE_NATIVE_FUNCTION(repl_help);
  59. JS_DECLARE_NATIVE_FUNCTION(load_file);
  60. JS_DECLARE_NATIVE_FUNCTION(save_to_file);
  61. };
  62. static bool s_dump_ast = false;
  63. static bool s_print_last_result = false;
  64. static RefPtr<Line::Editor> s_editor;
  65. static int s_repl_line_level = 0;
  66. static bool s_fail_repl = false;
  67. static String prompt_for_level(int level)
  68. {
  69. static StringBuilder prompt_builder;
  70. prompt_builder.clear();
  71. prompt_builder.append("> ");
  72. for (auto i = 0; i < level; ++i)
  73. prompt_builder.append(" ");
  74. return prompt_builder.build();
  75. }
  76. static String read_next_piece()
  77. {
  78. StringBuilder piece;
  79. auto line_level_delta_for_next_line { 0 };
  80. do {
  81. auto line_result = s_editor->get_line(prompt_for_level(s_repl_line_level));
  82. line_level_delta_for_next_line = 0;
  83. if (line_result.is_error()) {
  84. s_fail_repl = true;
  85. return "";
  86. }
  87. auto& line = line_result.value();
  88. s_editor->add_to_history(line);
  89. piece.append(line);
  90. auto lexer = JS::Lexer(line);
  91. enum {
  92. NotInLabelOrObjectKey,
  93. InLabelOrObjectKeyIdentifier,
  94. InLabelOrObjectKey
  95. } label_state { NotInLabelOrObjectKey };
  96. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  97. switch (token.type()) {
  98. case JS::TokenType::BracketOpen:
  99. case JS::TokenType::CurlyOpen:
  100. case JS::TokenType::ParenOpen:
  101. label_state = NotInLabelOrObjectKey;
  102. s_repl_line_level++;
  103. break;
  104. case JS::TokenType::BracketClose:
  105. case JS::TokenType::CurlyClose:
  106. case JS::TokenType::ParenClose:
  107. label_state = NotInLabelOrObjectKey;
  108. s_repl_line_level--;
  109. break;
  110. case JS::TokenType::Identifier:
  111. case JS::TokenType::StringLiteral:
  112. if (label_state == NotInLabelOrObjectKey)
  113. label_state = InLabelOrObjectKeyIdentifier;
  114. else
  115. label_state = NotInLabelOrObjectKey;
  116. break;
  117. case JS::TokenType::Colon:
  118. if (label_state == InLabelOrObjectKeyIdentifier)
  119. label_state = InLabelOrObjectKey;
  120. else
  121. label_state = NotInLabelOrObjectKey;
  122. break;
  123. default:
  124. break;
  125. }
  126. }
  127. if (label_state == InLabelOrObjectKey) {
  128. // If there's a label or object literal key at the end of this line,
  129. // prompt for more lines but do not change the line level.
  130. line_level_delta_for_next_line += 1;
  131. }
  132. } while (s_repl_line_level + line_level_delta_for_next_line > 0);
  133. return piece.to_string();
  134. }
  135. static void print_value(JS::Value value, HashTable<JS::Object*>& seen_objects);
  136. static void print_array(JS::Array& array, HashTable<JS::Object*>& seen_objects)
  137. {
  138. bool first = true;
  139. fputs("[ ", stdout);
  140. for (auto it = array.indexed_properties().begin(false); it != array.indexed_properties().end(); ++it) {
  141. if (!first)
  142. fputs(", ", stdout);
  143. first = false;
  144. auto value = it.value_and_attributes(&array).value;
  145. // The V8 repl doesn't throw an exception here, and instead just
  146. // prints 'undefined'. We may choose to replicate that behavior in
  147. // the future, but for now lets just catch the error
  148. if (vm->exception())
  149. return;
  150. print_value(value, seen_objects);
  151. }
  152. fputs(" ]", stdout);
  153. }
  154. static void print_object(JS::Object& object, HashTable<JS::Object*>& seen_objects)
  155. {
  156. fputs("{ ", stdout);
  157. bool first = true;
  158. for (auto& entry : object.indexed_properties()) {
  159. if (!first)
  160. fputs(", ", stdout);
  161. first = false;
  162. printf("\"\033[33;1m%d\033[0m\": ", entry.index());
  163. auto value = entry.value_and_attributes(&object).value;
  164. // The V8 repl doesn't throw an exception here, and instead just
  165. // prints 'undefined'. We may choose to replicate that behavior in
  166. // the future, but for now lets just catch the error
  167. if (vm->exception())
  168. return;
  169. print_value(value, seen_objects);
  170. }
  171. if (!object.indexed_properties().is_empty() && object.shape().property_count())
  172. fputs(", ", stdout);
  173. size_t index = 0;
  174. for (auto& it : object.shape().property_table_ordered()) {
  175. if (it.key.is_string()) {
  176. printf("\"\033[33;1m%s\033[0m\": ", it.key.to_display_string().characters());
  177. } else {
  178. printf("\033[33;1m%s\033[0m: ", it.key.to_display_string().characters());
  179. }
  180. print_value(object.get_direct(it.value.offset), seen_objects);
  181. if (index != object.shape().property_count() - 1)
  182. fputs(", ", stdout);
  183. ++index;
  184. }
  185. fputs(" }", stdout);
  186. }
  187. static void print_function(const JS::Object& function, HashTable<JS::Object*>&)
  188. {
  189. printf("\033[34;1m[%s]\033[0m", function.class_name());
  190. }
  191. static void print_date(const JS::Object& date, HashTable<JS::Object*>&)
  192. {
  193. printf("\033[34;1mDate %s\033[0m", static_cast<const JS::Date&>(date).string().characters());
  194. }
  195. static void print_error(const JS::Object& object, HashTable<JS::Object*>&)
  196. {
  197. auto& error = static_cast<const JS::Error&>(object);
  198. printf("\033[34;1m[%s]\033[0m", error.name().characters());
  199. if (!error.message().is_empty())
  200. printf(": %s", error.message().characters());
  201. }
  202. static void print_regexp(const JS::Object& object, HashTable<JS::Object*>&)
  203. {
  204. auto& regexp = static_cast<const JS::RegExpObject&>(object);
  205. printf("\033[34;1m/%s/%s\033[0m", regexp.content().characters(), regexp.flags().characters());
  206. }
  207. static void print_value(JS::Value value, HashTable<JS::Object*>& seen_objects)
  208. {
  209. if (value.is_empty()) {
  210. printf("\033[34;1m<empty>\033[0m");
  211. return;
  212. }
  213. if (value.is_object()) {
  214. if (seen_objects.contains(&value.as_object())) {
  215. // FIXME: Maybe we should only do this for circular references,
  216. // not for all reoccurring objects.
  217. printf("<already printed Object %p>", &value.as_object());
  218. return;
  219. }
  220. seen_objects.set(&value.as_object());
  221. }
  222. if (value.is_array())
  223. return print_array(static_cast<JS::Array&>(value.as_object()), seen_objects);
  224. if (value.is_object()) {
  225. auto& object = value.as_object();
  226. if (object.is_function())
  227. return print_function(object, seen_objects);
  228. if (object.is_date())
  229. return print_date(object, seen_objects);
  230. if (object.is_error())
  231. return print_error(object, seen_objects);
  232. if (object.is_regexp_object())
  233. return print_regexp(object, seen_objects);
  234. return print_object(object, seen_objects);
  235. }
  236. if (value.is_string())
  237. printf("\033[32;1m");
  238. else if (value.is_number() || value.is_bigint())
  239. printf("\033[35;1m");
  240. else if (value.is_boolean())
  241. printf("\033[33;1m");
  242. else if (value.is_null())
  243. printf("\033[33;1m");
  244. else if (value.is_undefined())
  245. printf("\033[34;1m");
  246. if (value.is_string())
  247. putchar('"');
  248. printf("%s", value.to_string_without_side_effects().characters());
  249. if (value.is_string())
  250. putchar('"');
  251. printf("\033[0m");
  252. }
  253. static void print(JS::Value value)
  254. {
  255. HashTable<JS::Object*> seen_objects;
  256. print_value(value, seen_objects);
  257. putchar('\n');
  258. }
  259. static bool file_has_shebang(AK::ByteBuffer file_contents)
  260. {
  261. if (file_contents.size() >= 2 && file_contents[0] == '#' && file_contents[1] == '!')
  262. return true;
  263. return false;
  264. }
  265. static StringView strip_shebang(AK::ByteBuffer file_contents)
  266. {
  267. size_t i = 0;
  268. for (i = 2; i < file_contents.size(); ++i) {
  269. if (file_contents[i] == '\n')
  270. break;
  271. }
  272. return StringView((const char*)file_contents.data() + i, file_contents.size() - i);
  273. }
  274. static bool write_to_file(const StringView& path)
  275. {
  276. int fd = open_with_path_length(path.characters_without_null_termination(), path.length(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  277. for (size_t i = 0; i < repl_statements.size(); i++) {
  278. auto line = repl_statements[i];
  279. if (line.length() && i != repl_statements.size() - 1) {
  280. ssize_t nwritten = write(fd, line.characters(), line.length());
  281. if (nwritten < 0) {
  282. close(fd);
  283. return false;
  284. }
  285. }
  286. if (i != repl_statements.size() - 1) {
  287. char ch = '\n';
  288. ssize_t nwritten = write(fd, &ch, 1);
  289. if (nwritten != 1) {
  290. perror("write");
  291. close(fd);
  292. return false;
  293. }
  294. }
  295. }
  296. close(fd);
  297. return true;
  298. }
  299. static bool parse_and_run(JS::Interpreter& interpreter, const StringView& source)
  300. {
  301. auto parser = JS::Parser(JS::Lexer(source));
  302. auto program = parser.parse_program();
  303. if (s_dump_ast)
  304. program->dump(0);
  305. if (parser.has_errors()) {
  306. auto error = parser.errors()[0];
  307. auto hint = error.source_location_hint(source);
  308. if (!hint.is_empty())
  309. printf("%s\n", hint.characters());
  310. interpreter.throw_exception<JS::SyntaxError>(error.to_string());
  311. } else {
  312. interpreter.run(interpreter.global_object(), *program);
  313. }
  314. if (vm->exception()) {
  315. printf("Uncaught exception: ");
  316. print(vm->exception()->value());
  317. auto trace = vm->exception()->trace();
  318. if (trace.size() > 1) {
  319. for (auto& function_name : trace)
  320. printf(" -> %s\n", function_name.characters());
  321. }
  322. interpreter.vm().clear_exception();
  323. return false;
  324. }
  325. if (s_print_last_result)
  326. print(interpreter.last_value());
  327. return true;
  328. }
  329. ReplObject::ReplObject()
  330. {
  331. }
  332. void ReplObject::initialize()
  333. {
  334. GlobalObject::initialize();
  335. define_property("global", this, JS::Attribute::Enumerable);
  336. define_native_function("exit", exit_interpreter);
  337. define_native_function("help", repl_help);
  338. define_native_function("load", load_file, 1);
  339. define_native_function("save", save_to_file, 1);
  340. }
  341. ReplObject::~ReplObject()
  342. {
  343. }
  344. JS_DEFINE_NATIVE_FUNCTION(ReplObject::save_to_file)
  345. {
  346. if (!interpreter.argument_count())
  347. return JS::Value(false);
  348. String save_path = interpreter.argument(0).to_string_without_side_effects();
  349. StringView path = StringView(save_path.characters());
  350. if (write_to_file(path)) {
  351. return JS::Value(true);
  352. }
  353. return JS::Value(false);
  354. }
  355. JS_DEFINE_NATIVE_FUNCTION(ReplObject::exit_interpreter)
  356. {
  357. if (!interpreter.argument_count())
  358. exit(0);
  359. auto exit_code = interpreter.argument(0).to_number(interpreter);
  360. if (::vm->exception())
  361. return {};
  362. exit(exit_code.as_double());
  363. }
  364. JS_DEFINE_NATIVE_FUNCTION(ReplObject::repl_help)
  365. {
  366. printf("REPL commands:\n");
  367. printf(" exit(code): exit the REPL with specified code. Defaults to 0.\n");
  368. printf(" help(): display this menu\n");
  369. printf(" load(files): accepts file names as params to load into running session. For example load(\"js/1.js\", \"js/2.js\", \"js/3.js\")\n");
  370. printf(" save(file): accepts a file name, writes REPL input history to a file. For example: save(\"foo.txt\")\n");
  371. return JS::js_undefined();
  372. }
  373. JS_DEFINE_NATIVE_FUNCTION(ReplObject::load_file)
  374. {
  375. if (!interpreter.argument_count())
  376. return JS::Value(false);
  377. for (auto& file : interpreter.call_frame().arguments) {
  378. String file_name = file.as_string().string();
  379. auto js_file = Core::File::construct(file_name);
  380. if (!js_file->open(Core::IODevice::ReadOnly)) {
  381. fprintf(stderr, "Failed to open %s: %s\n", file_name.characters(), js_file->error_string());
  382. }
  383. auto file_contents = js_file->read_all();
  384. StringView source;
  385. if (file_has_shebang(file_contents)) {
  386. source = strip_shebang(file_contents);
  387. } else {
  388. source = file_contents;
  389. }
  390. parse_and_run(interpreter, source);
  391. }
  392. return JS::Value(true);
  393. }
  394. static void repl(JS::Interpreter& interpreter)
  395. {
  396. while (!s_fail_repl) {
  397. String piece = read_next_piece();
  398. if (piece.is_empty())
  399. continue;
  400. repl_statements.append(piece);
  401. parse_and_run(interpreter, piece);
  402. }
  403. }
  404. static Function<void()> interrupt_interpreter;
  405. static void sigint_handler()
  406. {
  407. interrupt_interpreter();
  408. }
  409. class ReplConsoleClient final : public JS::ConsoleClient {
  410. public:
  411. ReplConsoleClient(JS::Console& console)
  412. : ConsoleClient(console)
  413. {
  414. }
  415. virtual JS::Value log() override
  416. {
  417. puts(interpreter().join_arguments().characters());
  418. return JS::js_undefined();
  419. }
  420. virtual JS::Value info() override
  421. {
  422. printf("(i) %s\n", interpreter().join_arguments().characters());
  423. return JS::js_undefined();
  424. }
  425. virtual JS::Value debug() override
  426. {
  427. printf("\033[36;1m");
  428. puts(interpreter().join_arguments().characters());
  429. printf("\033[0m");
  430. return JS::js_undefined();
  431. }
  432. virtual JS::Value warn() override
  433. {
  434. printf("\033[33;1m");
  435. puts(interpreter().join_arguments().characters());
  436. printf("\033[0m");
  437. return JS::js_undefined();
  438. }
  439. virtual JS::Value error() override
  440. {
  441. printf("\033[31;1m");
  442. puts(interpreter().join_arguments().characters());
  443. printf("\033[0m");
  444. return JS::js_undefined();
  445. }
  446. virtual JS::Value clear() override
  447. {
  448. printf("\033[3J\033[H\033[2J");
  449. fflush(stdout);
  450. return JS::js_undefined();
  451. }
  452. virtual JS::Value trace() override
  453. {
  454. puts(interpreter().join_arguments().characters());
  455. auto trace = get_trace();
  456. for (auto& function_name : trace) {
  457. if (function_name.is_empty())
  458. function_name = "<anonymous>";
  459. printf(" -> %s\n", function_name.characters());
  460. }
  461. return JS::js_undefined();
  462. }
  463. virtual JS::Value count() override
  464. {
  465. auto label = interpreter().argument_count() ? interpreter().argument(0).to_string_without_side_effects() : "default";
  466. auto counter_value = m_console.counter_increment(label);
  467. printf("%s: %u\n", label.characters(), counter_value);
  468. return JS::js_undefined();
  469. }
  470. virtual JS::Value count_reset() override
  471. {
  472. auto label = interpreter().argument_count() ? interpreter().argument(0).to_string_without_side_effects() : "default";
  473. if (m_console.counter_reset(label)) {
  474. printf("%s: 0\n", label.characters());
  475. } else {
  476. printf("\033[33;1m");
  477. printf("\"%s\" doesn't have a count\n", label.characters());
  478. printf("\033[0m");
  479. }
  480. return JS::js_undefined();
  481. }
  482. };
  483. int main(int argc, char** argv)
  484. {
  485. bool gc_on_every_allocation = false;
  486. bool disable_syntax_highlight = false;
  487. const char* script_path = nullptr;
  488. Core::ArgsParser args_parser;
  489. args_parser.add_option(s_dump_ast, "Dump the AST", "dump-ast", 'A');
  490. args_parser.add_option(s_print_last_result, "Print last result", "print-last-result", 'l');
  491. args_parser.add_option(gc_on_every_allocation, "GC on every allocation", "gc-on-every-allocation", 'g');
  492. args_parser.add_option(disable_syntax_highlight, "Disable live syntax highlighting", "no-syntax-highlight", 's');
  493. args_parser.add_positional_argument(script_path, "Path to script file", "script", Core::ArgsParser::Required::No);
  494. args_parser.parse(argc, argv);
  495. bool syntax_highlight = !disable_syntax_highlight;
  496. vm = JS::VM::create();
  497. OwnPtr<JS::Interpreter> interpreter;
  498. interrupt_interpreter = [&] {
  499. auto error = JS::Error::create(interpreter->global_object(), "Error", "Received SIGINT");
  500. interpreter->throw_exception(error);
  501. };
  502. if (script_path == nullptr) {
  503. s_print_last_result = true;
  504. interpreter = JS::Interpreter::create<ReplObject>(*vm);
  505. ReplConsoleClient console_client(interpreter->console());
  506. interpreter->console().set_client(console_client);
  507. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  508. interpreter->set_underscore_is_last_value(true);
  509. s_editor = Line::Editor::construct();
  510. signal(SIGINT, [](int) {
  511. if (!s_editor->is_editing())
  512. sigint_handler();
  513. });
  514. s_editor->on_display_refresh = [syntax_highlight](Line::Editor& editor) {
  515. auto stylize = [&](Line::Span span, Line::Style styles) {
  516. if (syntax_highlight)
  517. editor.stylize(span, styles);
  518. };
  519. editor.strip_styles();
  520. size_t open_indents = s_repl_line_level;
  521. auto line = editor.line();
  522. JS::Lexer lexer(line);
  523. bool indenters_starting_line = true;
  524. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  525. auto length = token.value().length();
  526. auto start = token.line_column() - 1;
  527. auto end = start + length;
  528. if (indenters_starting_line) {
  529. if (token.type() != JS::TokenType::ParenClose && token.type() != JS::TokenType::BracketClose && token.type() != JS::TokenType::CurlyClose) {
  530. indenters_starting_line = false;
  531. } else {
  532. --open_indents;
  533. }
  534. }
  535. switch (token.type()) {
  536. case JS::TokenType::Invalid:
  537. case JS::TokenType::Eof:
  538. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Red), Line::Style::Underline });
  539. break;
  540. case JS::TokenType::NumericLiteral:
  541. case JS::TokenType::BigIntLiteral:
  542. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Magenta) });
  543. break;
  544. case JS::TokenType::StringLiteral:
  545. case JS::TokenType::TemplateLiteralStart:
  546. case JS::TokenType::TemplateLiteralEnd:
  547. case JS::TokenType::TemplateLiteralString:
  548. case JS::TokenType::RegexLiteral:
  549. case JS::TokenType::RegexFlags:
  550. case JS::TokenType::UnterminatedStringLiteral:
  551. case JS::TokenType::UnterminatedRegexLiteral:
  552. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Green), Line::Style::Bold });
  553. break;
  554. case JS::TokenType::BracketClose:
  555. case JS::TokenType::BracketOpen:
  556. case JS::TokenType::Comma:
  557. case JS::TokenType::CurlyClose:
  558. case JS::TokenType::CurlyOpen:
  559. case JS::TokenType::ParenClose:
  560. case JS::TokenType::ParenOpen:
  561. case JS::TokenType::Semicolon:
  562. case JS::TokenType::Period:
  563. break;
  564. case JS::TokenType::Ampersand:
  565. case JS::TokenType::AmpersandEquals:
  566. case JS::TokenType::Asterisk:
  567. case JS::TokenType::DoubleAsteriskEquals:
  568. case JS::TokenType::AsteriskEquals:
  569. case JS::TokenType::Caret:
  570. case JS::TokenType::CaretEquals:
  571. case JS::TokenType::DoubleAmpersand:
  572. case JS::TokenType::DoubleAsterisk:
  573. case JS::TokenType::DoublePipe:
  574. case JS::TokenType::DoubleQuestionMark:
  575. case JS::TokenType::Equals:
  576. case JS::TokenType::EqualsEquals:
  577. case JS::TokenType::EqualsEqualsEquals:
  578. case JS::TokenType::ExclamationMark:
  579. case JS::TokenType::ExclamationMarkEquals:
  580. case JS::TokenType::ExclamationMarkEqualsEquals:
  581. case JS::TokenType::GreaterThan:
  582. case JS::TokenType::GreaterThanEquals:
  583. case JS::TokenType::LessThan:
  584. case JS::TokenType::LessThanEquals:
  585. case JS::TokenType::Minus:
  586. case JS::TokenType::MinusEquals:
  587. case JS::TokenType::MinusMinus:
  588. case JS::TokenType::Percent:
  589. case JS::TokenType::PercentEquals:
  590. case JS::TokenType::Pipe:
  591. case JS::TokenType::PipeEquals:
  592. case JS::TokenType::Plus:
  593. case JS::TokenType::PlusEquals:
  594. case JS::TokenType::PlusPlus:
  595. case JS::TokenType::QuestionMark:
  596. case JS::TokenType::QuestionMarkPeriod:
  597. case JS::TokenType::ShiftLeft:
  598. case JS::TokenType::ShiftLeftEquals:
  599. case JS::TokenType::ShiftRight:
  600. case JS::TokenType::ShiftRightEquals:
  601. case JS::TokenType::Slash:
  602. case JS::TokenType::SlashEquals:
  603. case JS::TokenType::Tilde:
  604. case JS::TokenType::UnsignedShiftRight:
  605. case JS::TokenType::UnsignedShiftRightEquals:
  606. break;
  607. case JS::TokenType::BoolLiteral:
  608. case JS::TokenType::NullLiteral:
  609. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow), Line::Style::Bold });
  610. break;
  611. case JS::TokenType::Class:
  612. case JS::TokenType::Const:
  613. case JS::TokenType::Debugger:
  614. case JS::TokenType::Delete:
  615. case JS::TokenType::Extends:
  616. case JS::TokenType::Function:
  617. case JS::TokenType::In:
  618. case JS::TokenType::Instanceof:
  619. case JS::TokenType::Interface:
  620. case JS::TokenType::Let:
  621. case JS::TokenType::New:
  622. case JS::TokenType::Super:
  623. case JS::TokenType::TemplateLiteralExprStart:
  624. case JS::TokenType::TemplateLiteralExprEnd:
  625. case JS::TokenType::Throw:
  626. case JS::TokenType::Typeof:
  627. case JS::TokenType::Var:
  628. case JS::TokenType::Void:
  629. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Blue), Line::Style::Bold });
  630. break;
  631. case JS::TokenType::Await:
  632. case JS::TokenType::Case:
  633. case JS::TokenType::Catch:
  634. case JS::TokenType::Do:
  635. case JS::TokenType::Else:
  636. case JS::TokenType::Finally:
  637. case JS::TokenType::For:
  638. case JS::TokenType::If:
  639. case JS::TokenType::Return:
  640. case JS::TokenType::Switch:
  641. case JS::TokenType::Try:
  642. case JS::TokenType::While:
  643. case JS::TokenType::Yield:
  644. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan), Line::Style::Italic });
  645. break;
  646. case JS::TokenType::Identifier:
  647. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::White), Line::Style::Bold });
  648. default:
  649. break;
  650. }
  651. }
  652. editor.set_prompt(prompt_for_level(open_indents));
  653. };
  654. auto complete = [&interpreter](const Line::Editor& editor) -> Vector<Line::CompletionSuggestion> {
  655. auto line = editor.line(editor.cursor());
  656. JS::Lexer lexer { line };
  657. enum {
  658. Initial,
  659. CompleteVariable,
  660. CompleteNullProperty,
  661. CompleteProperty,
  662. } mode { Initial };
  663. StringView variable_name;
  664. StringView property_name;
  665. // we're only going to complete either
  666. // - <N>
  667. // where N is part of the name of a variable
  668. // - <N>.<P>
  669. // where N is the complete name of a variable and
  670. // P is part of the name of one of its properties
  671. auto js_token = lexer.next();
  672. for (; js_token.type() != JS::TokenType::Eof; js_token = lexer.next()) {
  673. switch (mode) {
  674. case CompleteVariable:
  675. switch (js_token.type()) {
  676. case JS::TokenType::Period:
  677. // ...<name> <dot>
  678. mode = CompleteNullProperty;
  679. break;
  680. default:
  681. // not a dot, reset back to initial
  682. mode = Initial;
  683. break;
  684. }
  685. break;
  686. case CompleteNullProperty:
  687. if (js_token.is_identifier_name()) {
  688. // ...<name> <dot> <name>
  689. mode = CompleteProperty;
  690. property_name = js_token.value();
  691. } else {
  692. mode = Initial;
  693. }
  694. break;
  695. case CompleteProperty:
  696. // something came after the property access, reset to initial
  697. case Initial:
  698. if (js_token.is_identifier_name()) {
  699. // ...<name>...
  700. mode = CompleteVariable;
  701. variable_name = js_token.value();
  702. } else {
  703. mode = Initial;
  704. }
  705. break;
  706. }
  707. }
  708. bool last_token_has_trivia = js_token.trivia().length() > 0;
  709. if (mode == CompleteNullProperty) {
  710. mode = CompleteProperty;
  711. property_name = "";
  712. last_token_has_trivia = false; // <name> <dot> [tab] is sensible to complete.
  713. }
  714. if (mode == Initial || last_token_has_trivia)
  715. return {}; // we do not know how to complete this
  716. Vector<Line::CompletionSuggestion> results;
  717. Function<void(const JS::Shape&, const StringView&)> list_all_properties = [&results, &list_all_properties](const JS::Shape& shape, auto& property_pattern) {
  718. for (const auto& descriptor : shape.property_table()) {
  719. if (!descriptor.key.is_string())
  720. continue;
  721. auto key = descriptor.key.as_string();
  722. if (key.view().starts_with(property_pattern)) {
  723. Line::CompletionSuggestion completion { key, Line::CompletionSuggestion::ForSearch };
  724. if (!results.contains_slow(completion)) { // hide duplicates
  725. results.append(key);
  726. }
  727. }
  728. }
  729. if (const auto* prototype = shape.prototype()) {
  730. list_all_properties(prototype->shape(), property_pattern);
  731. }
  732. };
  733. switch (mode) {
  734. case CompleteProperty: {
  735. auto maybe_variable = interpreter->get_variable(variable_name, interpreter->global_object());
  736. if (maybe_variable.is_empty()) {
  737. maybe_variable = interpreter->global_object().get(FlyString(variable_name));
  738. if (maybe_variable.is_empty())
  739. break;
  740. }
  741. auto variable = maybe_variable;
  742. if (!variable.is_object())
  743. break;
  744. const auto* object = variable.to_object(*interpreter, interpreter->global_object());
  745. const auto& shape = object->shape();
  746. list_all_properties(shape, property_name);
  747. if (results.size())
  748. editor.suggest(property_name.length());
  749. break;
  750. }
  751. case CompleteVariable: {
  752. const auto& variable = interpreter->global_object();
  753. list_all_properties(variable.shape(), variable_name);
  754. if (results.size())
  755. editor.suggest(variable_name.length());
  756. break;
  757. }
  758. default:
  759. ASSERT_NOT_REACHED();
  760. }
  761. return results;
  762. };
  763. s_editor->on_tab_complete = move(complete);
  764. repl(*interpreter);
  765. } else {
  766. interpreter = JS::Interpreter::create<JS::GlobalObject>(*vm);
  767. ReplConsoleClient console_client(interpreter->console());
  768. interpreter->console().set_client(console_client);
  769. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  770. signal(SIGINT, [](int) {
  771. sigint_handler();
  772. });
  773. auto file = Core::File::construct(script_path);
  774. if (!file->open(Core::IODevice::ReadOnly)) {
  775. fprintf(stderr, "Failed to open %s: %s\n", script_path, file->error_string());
  776. return 1;
  777. }
  778. auto file_contents = file->read_all();
  779. StringView source;
  780. if (file_has_shebang(file_contents)) {
  781. source = strip_shebang(file_contents);
  782. } else {
  783. source = file_contents;
  784. }
  785. if (!parse_and_run(*interpreter, source))
  786. return 1;
  787. }
  788. return 0;
  789. }