js.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  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/Shape.h>
  43. #include <LibJS/Runtime/Value.h>
  44. #include <LibLine/Editor.h>
  45. #include <signal.h>
  46. #include <stdio.h>
  47. Vector<String> repl_statements;
  48. class ReplObject : public JS::GlobalObject {
  49. public:
  50. ReplObject();
  51. virtual void initialize() override;
  52. virtual ~ReplObject() override;
  53. static JS::Value load_file(JS::Interpreter&);
  54. private:
  55. virtual const char* class_name() const override { return "ReplObject"; }
  56. static JS::Value exit_interpreter(JS::Interpreter&);
  57. static JS::Value repl_help(JS::Interpreter&);
  58. static JS::Value save_to_file(JS::Interpreter&);
  59. };
  60. static bool s_dump_ast = false;
  61. static bool s_print_last_result = false;
  62. static OwnPtr<Line::Editor> s_editor;
  63. static int s_repl_line_level = 0;
  64. static String prompt_for_level(int level)
  65. {
  66. static StringBuilder prompt_builder;
  67. prompt_builder.clear();
  68. prompt_builder.append("> ");
  69. for (auto i = 0; i < level; ++i)
  70. prompt_builder.append(" ");
  71. return prompt_builder.build();
  72. }
  73. String read_next_piece()
  74. {
  75. StringBuilder piece;
  76. do {
  77. String line = s_editor->get_line(prompt_for_level(s_repl_line_level));
  78. s_editor->add_to_history(line);
  79. piece.append(line);
  80. auto lexer = JS::Lexer(line);
  81. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  82. switch (token.type()) {
  83. case JS::TokenType::BracketOpen:
  84. case JS::TokenType::CurlyOpen:
  85. case JS::TokenType::ParenOpen:
  86. s_repl_line_level++;
  87. break;
  88. case JS::TokenType::BracketClose:
  89. case JS::TokenType::CurlyClose:
  90. case JS::TokenType::ParenClose:
  91. s_repl_line_level--;
  92. break;
  93. default:
  94. break;
  95. }
  96. }
  97. } while (s_repl_line_level > 0);
  98. return piece.to_string();
  99. }
  100. static void print_value(JS::Value value, HashTable<JS::Object*>& seen_objects);
  101. static void print_array(const JS::Array& array, HashTable<JS::Object*>& seen_objects)
  102. {
  103. fputs("[ ", stdout);
  104. for (size_t i = 0; i < array.elements().size(); ++i) {
  105. print_value(array.elements()[i], seen_objects);
  106. if (i != array.elements().size() - 1)
  107. fputs(", ", stdout);
  108. }
  109. fputs(" ]", stdout);
  110. }
  111. static void print_object(const JS::Object& object, HashTable<JS::Object*>& seen_objects)
  112. {
  113. fputs("{ ", stdout);
  114. for (size_t i = 0; i < object.elements().size(); ++i) {
  115. if (object.elements()[i].is_empty())
  116. continue;
  117. printf("\"\033[33;1m%zu\033[0m\": ", i);
  118. print_value(object.elements()[i], seen_objects);
  119. if (i != object.elements().size() - 1)
  120. fputs(", ", stdout);
  121. }
  122. if (!object.elements().is_empty() && object.shape().property_count())
  123. fputs(", ", stdout);
  124. size_t index = 0;
  125. for (auto& it : object.shape().property_table_ordered()) {
  126. printf("\"\033[33;1m%s\033[0m\": ", it.key.characters());
  127. print_value(object.get_direct(it.value.offset), seen_objects);
  128. if (index != object.shape().property_count() - 1)
  129. fputs(", ", stdout);
  130. ++index;
  131. }
  132. fputs(" }", stdout);
  133. }
  134. static void print_function(const JS::Object& function, HashTable<JS::Object*>&)
  135. {
  136. printf("\033[34;1m[%s]\033[0m", function.class_name());
  137. }
  138. static void print_date(const JS::Object& date, HashTable<JS::Object*>&)
  139. {
  140. printf("\033[34;1mDate %s\033[0m", static_cast<const JS::Date&>(date).string().characters());
  141. }
  142. static void print_error(const JS::Object& object, HashTable<JS::Object*>&)
  143. {
  144. auto& error = static_cast<const JS::Error&>(object);
  145. printf("\033[34;1m[%s]\033[0m", error.name().characters());
  146. if (!error.message().is_empty())
  147. printf(": %s", error.message().characters());
  148. }
  149. void print_value(JS::Value value, HashTable<JS::Object*>& seen_objects)
  150. {
  151. if (value.is_empty()) {
  152. printf("\033[34;1m<empty>\033[0m");
  153. return;
  154. }
  155. if (value.is_object()) {
  156. if (seen_objects.contains(&value.as_object())) {
  157. // FIXME: Maybe we should only do this for circular references,
  158. // not for all reoccurring objects.
  159. printf("<already printed Object %p>", &value.as_object());
  160. return;
  161. }
  162. seen_objects.set(&value.as_object());
  163. }
  164. if (value.is_array())
  165. return print_array(static_cast<const JS::Array&>(value.as_object()), seen_objects);
  166. if (value.is_object()) {
  167. auto& object = value.as_object();
  168. if (object.is_function())
  169. return print_function(object, seen_objects);
  170. if (object.is_date())
  171. return print_date(object, seen_objects);
  172. if (object.is_error())
  173. return print_error(object, seen_objects);
  174. return print_object(object, seen_objects);
  175. }
  176. if (value.is_string())
  177. printf("\033[32;1m");
  178. else if (value.is_number())
  179. printf("\033[35;1m");
  180. else if (value.is_boolean())
  181. printf("\033[33;1m");
  182. else if (value.is_null())
  183. printf("\033[33;1m");
  184. else if (value.is_undefined())
  185. printf("\033[34;1m");
  186. if (value.is_string())
  187. putchar('"');
  188. printf("%s", value.to_string().characters());
  189. if (value.is_string())
  190. putchar('"');
  191. printf("\033[0m");
  192. }
  193. static void print(JS::Value value)
  194. {
  195. HashTable<JS::Object*> seen_objects;
  196. print_value(value, seen_objects);
  197. putchar('\n');
  198. }
  199. bool file_has_shebang(AK::ByteBuffer file_contents)
  200. {
  201. if (file_contents.size() >= 2 && file_contents[0] == '#' && file_contents[1] == '!')
  202. return true;
  203. return false;
  204. }
  205. StringView strip_shebang(AK::ByteBuffer file_contents)
  206. {
  207. size_t i = 0;
  208. for (i = 2; i < file_contents.size(); ++i) {
  209. if (file_contents[i] == '\n')
  210. break;
  211. }
  212. return StringView((const char*)file_contents.data() + i, file_contents.size() - i);
  213. }
  214. bool write_to_file(const StringView& path)
  215. {
  216. int fd = open_with_path_length(path.characters_without_null_termination(), path.length(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  217. for (size_t i = 0; i < repl_statements.size(); i++) {
  218. auto line = repl_statements[i];
  219. if (line.length() && i != repl_statements.size() - 1) {
  220. ssize_t nwritten = write(fd, line.characters(), line.length());
  221. if (nwritten < 0) {
  222. close(fd);
  223. return false;
  224. }
  225. }
  226. if (i != repl_statements.size() - 1) {
  227. char ch = '\n';
  228. ssize_t nwritten = write(fd, &ch, 1);
  229. if (nwritten != 1) {
  230. perror("write");
  231. close(fd);
  232. return false;
  233. }
  234. }
  235. }
  236. close(fd);
  237. return true;
  238. }
  239. ReplObject::ReplObject()
  240. {
  241. }
  242. void ReplObject::initialize()
  243. {
  244. GlobalObject::initialize();
  245. put_native_function("exit", exit_interpreter);
  246. put_native_function("help", repl_help);
  247. put_native_function("load", load_file, 1);
  248. put_native_function("save", save_to_file, 1);
  249. }
  250. ReplObject::~ReplObject()
  251. {
  252. }
  253. JS::Value ReplObject::save_to_file(JS::Interpreter& interpreter)
  254. {
  255. if (!interpreter.argument_count())
  256. return JS::Value(false);
  257. String save_path = interpreter.argument(0).to_string();
  258. StringView path = StringView(save_path.characters());
  259. if (write_to_file(path)) {
  260. return JS::Value(true);
  261. }
  262. return JS::Value(false);
  263. }
  264. JS::Value ReplObject::exit_interpreter(JS::Interpreter& interpreter)
  265. {
  266. if (!interpreter.argument_count())
  267. exit(0);
  268. int exit_code = interpreter.argument(0).to_number().as_double();
  269. exit(exit_code);
  270. return JS::js_undefined();
  271. }
  272. JS::Value ReplObject::repl_help(JS::Interpreter&)
  273. {
  274. printf("REPL commands:\n");
  275. printf(" exit(code): exit the REPL with specified code. Defaults to 0.\n");
  276. printf(" help(): display this menu\n");
  277. 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");
  278. return JS::js_undefined();
  279. }
  280. JS::Value ReplObject::load_file(JS::Interpreter& interpreter)
  281. {
  282. if (!interpreter.argument_count())
  283. return JS::Value(false);
  284. for (auto& file : interpreter.call_frame().arguments) {
  285. String file_name = file.as_string().string();
  286. auto js_file = Core::File::construct(file_name);
  287. if (!js_file->open(Core::IODevice::ReadOnly)) {
  288. fprintf(stderr, "Failed to open %s: %s\n", file_name.characters(), js_file->error_string());
  289. }
  290. auto file_contents = js_file->read_all();
  291. StringView source;
  292. if (file_has_shebang(file_contents)) {
  293. source = strip_shebang(file_contents);
  294. } else {
  295. source = file_contents;
  296. }
  297. auto parser = JS::Parser(JS::Lexer(source));
  298. auto program = parser.parse_program();
  299. if (s_dump_ast)
  300. program->dump(0);
  301. if (parser.has_errors())
  302. continue;
  303. interpreter.run(*program);
  304. if (s_print_last_result)
  305. print(interpreter.last_value());
  306. }
  307. return JS::Value(true);
  308. }
  309. void repl(JS::Interpreter& interpreter)
  310. {
  311. while (true) {
  312. String piece = read_next_piece();
  313. if (piece.is_empty())
  314. continue;
  315. repl_statements.append(piece);
  316. auto parser = JS::Parser(JS::Lexer(piece));
  317. auto program = parser.parse_program();
  318. if (s_dump_ast)
  319. program->dump(0);
  320. if (parser.has_errors()) {
  321. printf("Parse error\n");
  322. continue;
  323. }
  324. interpreter.run(*program);
  325. if (interpreter.exception()) {
  326. printf("Uncaught exception: ");
  327. print(interpreter.exception()->value());
  328. interpreter.clear_exception();
  329. } else {
  330. print(interpreter.last_value());
  331. }
  332. }
  333. }
  334. void enable_test_mode(JS::Interpreter& interpreter)
  335. {
  336. interpreter.global_object().put_native_function("load", ReplObject::load_file);
  337. }
  338. static Function<void()> interrupt_interpreter;
  339. void sigint_handler()
  340. {
  341. interrupt_interpreter();
  342. }
  343. class ReplConsoleClient final : public JS::ConsoleClient {
  344. public:
  345. ReplConsoleClient(JS::Console& console)
  346. : ConsoleClient(console)
  347. {
  348. }
  349. virtual JS::Value log() override
  350. {
  351. puts(interpreter().join_arguments().characters());
  352. return JS::js_undefined();
  353. }
  354. virtual JS::Value info() override
  355. {
  356. printf("(i) %s\n", interpreter().join_arguments().characters());
  357. return JS::js_undefined();
  358. }
  359. virtual JS::Value debug() override
  360. {
  361. printf("\033[36;1m");
  362. puts(interpreter().join_arguments().characters());
  363. printf("\033[0m");
  364. return JS::js_undefined();
  365. }
  366. virtual JS::Value warn() override
  367. {
  368. printf("\033[33;1m");
  369. puts(interpreter().join_arguments().characters());
  370. printf("\033[0m");
  371. return JS::js_undefined();
  372. }
  373. virtual JS::Value error() override
  374. {
  375. printf("\033[31;1m");
  376. puts(interpreter().join_arguments().characters());
  377. printf("\033[0m");
  378. return JS::js_undefined();
  379. }
  380. virtual JS::Value clear() override
  381. {
  382. printf("\033[3J\033[H\033[2J");
  383. fflush(stdout);
  384. return JS::js_undefined();
  385. }
  386. virtual JS::Value trace() override
  387. {
  388. puts(interpreter().join_arguments().characters());
  389. auto trace = interpreter().get_trace();
  390. for (auto& function_name : trace) {
  391. if (function_name.is_empty())
  392. function_name = "<anonymous>";
  393. printf(" -> %s\n", function_name.characters());
  394. }
  395. return JS::js_undefined();
  396. }
  397. virtual JS::Value count() override
  398. {
  399. auto label = interpreter().argument_count() ? interpreter().argument(0).to_string() : "default";
  400. auto counter_value = m_console.counter_increment(label);
  401. printf("%s: %u\n", label.characters(), counter_value);
  402. return JS::js_undefined();
  403. }
  404. virtual JS::Value count_reset() override
  405. {
  406. auto label = interpreter().argument_count() ? interpreter().argument(0).to_string() : "default";
  407. if (m_console.counter_reset(label)) {
  408. printf("%s: 0\n", label.characters());
  409. } else {
  410. printf("\033[33;1m");
  411. printf("\"%s\" doesn't have a count\n", label.characters());
  412. printf("\033[0m");
  413. }
  414. return JS::js_undefined();
  415. }
  416. };
  417. int main(int argc, char** argv)
  418. {
  419. bool gc_on_every_allocation = false;
  420. bool disable_syntax_highlight = false;
  421. bool test_mode = false;
  422. const char* script_path = nullptr;
  423. Core::ArgsParser args_parser;
  424. args_parser.add_option(s_dump_ast, "Dump the AST", "dump-ast", 'A');
  425. args_parser.add_option(s_print_last_result, "Print last result", "print-last-result", 'l');
  426. args_parser.add_option(gc_on_every_allocation, "GC on every allocation", "gc-on-every-allocation", 'g');
  427. args_parser.add_option(disable_syntax_highlight, "Disable live syntax highlighting", "no-syntax-highlight", 's');
  428. args_parser.add_option(test_mode, "Run the interpreter with added functionality for the test harness", "test-mode", 't');
  429. args_parser.add_positional_argument(script_path, "Path to script file", "script", Core::ArgsParser::Required::No);
  430. args_parser.parse(argc, argv);
  431. bool syntax_highlight = !disable_syntax_highlight;
  432. OwnPtr<JS::Interpreter> interpreter;
  433. interrupt_interpreter = [&] {
  434. auto error = JS::Error::create(interpreter->global_object(), "Error", "Received SIGINT");
  435. interpreter->throw_exception(error);
  436. };
  437. if (script_path == nullptr) {
  438. interpreter = JS::Interpreter::create<ReplObject>();
  439. ReplConsoleClient console_client(interpreter->console());
  440. interpreter->console().set_client(console_client);
  441. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  442. if (test_mode)
  443. enable_test_mode(*interpreter);
  444. s_editor = make<Line::Editor>();
  445. signal(SIGINT, [](int) {
  446. if (!s_editor->is_editing())
  447. sigint_handler();
  448. s_editor->interrupted();
  449. });
  450. signal(SIGWINCH, [](int) {
  451. s_editor->resized();
  452. });
  453. s_editor->on_display_refresh = [syntax_highlight](Line::Editor& editor) {
  454. auto stylize = [&](Line::Span span, Line::Style styles) {
  455. if (syntax_highlight)
  456. editor.stylize(span, styles);
  457. };
  458. editor.strip_styles();
  459. StringBuilder builder;
  460. builder.append({ editor.buffer().data(), editor.buffer().size() });
  461. // FIXME: The lexer returns weird position information without this
  462. builder.append(" ");
  463. String str = builder.build();
  464. size_t open_indents = s_repl_line_level;
  465. JS::Lexer lexer(str);
  466. bool indenters_starting_line = true;
  467. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  468. auto length = token.value().length();
  469. auto start = token.line_column() - 2;
  470. auto end = start + length;
  471. if (indenters_starting_line) {
  472. if (token.type() != JS::TokenType::ParenClose && token.type() != JS::TokenType::BracketClose && token.type() != JS::TokenType::CurlyClose) {
  473. indenters_starting_line = false;
  474. } else {
  475. --open_indents;
  476. }
  477. }
  478. switch (token.type()) {
  479. case JS::TokenType::Invalid:
  480. case JS::TokenType::Eof:
  481. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Red), Line::Style::Underline });
  482. break;
  483. case JS::TokenType::NumericLiteral:
  484. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Magenta) });
  485. break;
  486. case JS::TokenType::StringLiteral:
  487. case JS::TokenType::TemplateLiteralStart:
  488. case JS::TokenType::TemplateLiteralEnd:
  489. case JS::TokenType::TemplateLiteralString:
  490. case JS::TokenType::RegexLiteral:
  491. case JS::TokenType::UnterminatedStringLiteral:
  492. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Green), Line::Style::Bold });
  493. break;
  494. case JS::TokenType::BracketClose:
  495. case JS::TokenType::BracketOpen:
  496. case JS::TokenType::Comma:
  497. case JS::TokenType::CurlyClose:
  498. case JS::TokenType::CurlyOpen:
  499. case JS::TokenType::ParenClose:
  500. case JS::TokenType::ParenOpen:
  501. case JS::TokenType::Semicolon:
  502. case JS::TokenType::Period:
  503. break;
  504. case JS::TokenType::Ampersand:
  505. case JS::TokenType::AmpersandEquals:
  506. case JS::TokenType::Asterisk:
  507. case JS::TokenType::DoubleAsteriskEquals:
  508. case JS::TokenType::AsteriskEquals:
  509. case JS::TokenType::Caret:
  510. case JS::TokenType::CaretEquals:
  511. case JS::TokenType::DoubleAmpersand:
  512. case JS::TokenType::DoubleAsterisk:
  513. case JS::TokenType::DoublePipe:
  514. case JS::TokenType::DoubleQuestionMark:
  515. case JS::TokenType::Equals:
  516. case JS::TokenType::EqualsEquals:
  517. case JS::TokenType::EqualsEqualsEquals:
  518. case JS::TokenType::ExclamationMark:
  519. case JS::TokenType::ExclamationMarkEquals:
  520. case JS::TokenType::ExclamationMarkEqualsEquals:
  521. case JS::TokenType::GreaterThan:
  522. case JS::TokenType::GreaterThanEquals:
  523. case JS::TokenType::LessThan:
  524. case JS::TokenType::LessThanEquals:
  525. case JS::TokenType::Minus:
  526. case JS::TokenType::MinusEquals:
  527. case JS::TokenType::MinusMinus:
  528. case JS::TokenType::Percent:
  529. case JS::TokenType::PercentEquals:
  530. case JS::TokenType::Pipe:
  531. case JS::TokenType::PipeEquals:
  532. case JS::TokenType::Plus:
  533. case JS::TokenType::PlusEquals:
  534. case JS::TokenType::PlusPlus:
  535. case JS::TokenType::QuestionMark:
  536. case JS::TokenType::QuestionMarkPeriod:
  537. case JS::TokenType::ShiftLeft:
  538. case JS::TokenType::ShiftLeftEquals:
  539. case JS::TokenType::ShiftRight:
  540. case JS::TokenType::ShiftRightEquals:
  541. case JS::TokenType::Slash:
  542. case JS::TokenType::SlashEquals:
  543. case JS::TokenType::Tilde:
  544. case JS::TokenType::UnsignedShiftRight:
  545. case JS::TokenType::UnsignedShiftRightEquals:
  546. break;
  547. case JS::TokenType::BoolLiteral:
  548. case JS::TokenType::NullLiteral:
  549. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow), Line::Style::Bold });
  550. break;
  551. case JS::TokenType::Class:
  552. case JS::TokenType::Const:
  553. case JS::TokenType::Debugger:
  554. case JS::TokenType::Delete:
  555. case JS::TokenType::Function:
  556. case JS::TokenType::In:
  557. case JS::TokenType::Instanceof:
  558. case JS::TokenType::Interface:
  559. case JS::TokenType::Let:
  560. case JS::TokenType::New:
  561. case JS::TokenType::TemplateLiteralExprStart:
  562. case JS::TokenType::TemplateLiteralExprEnd:
  563. case JS::TokenType::Throw:
  564. case JS::TokenType::Typeof:
  565. case JS::TokenType::Var:
  566. case JS::TokenType::Void:
  567. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Blue), Line::Style::Bold });
  568. break;
  569. case JS::TokenType::Await:
  570. case JS::TokenType::Case:
  571. case JS::TokenType::Catch:
  572. case JS::TokenType::Do:
  573. case JS::TokenType::Else:
  574. case JS::TokenType::Finally:
  575. case JS::TokenType::For:
  576. case JS::TokenType::If:
  577. case JS::TokenType::Return:
  578. case JS::TokenType::Switch:
  579. case JS::TokenType::Try:
  580. case JS::TokenType::While:
  581. case JS::TokenType::Yield:
  582. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan), Line::Style::Italic });
  583. break;
  584. case JS::TokenType::Identifier:
  585. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::White), Line::Style::Bold });
  586. default:
  587. break;
  588. }
  589. }
  590. editor.set_prompt(prompt_for_level(open_indents));
  591. };
  592. auto complete = [&interpreter, &editor = *s_editor](const String& token) -> Vector<Line::CompletionSuggestion> {
  593. if (token.length() == 0)
  594. return {}; // nyeh
  595. StringView line { editor.buffer().data(), editor.cursor() };
  596. // we're only going to complete either
  597. // - <N>
  598. // where N is part of the name of a variable
  599. // - <N>.<P>
  600. // where N is the complete name of a variable and
  601. // P is part of the name of one of its properties
  602. Vector<Line::CompletionSuggestion> results;
  603. Function<void(const JS::Shape&, const StringView&)> list_all_properties = [&results, &list_all_properties](const JS::Shape& shape, auto& property_pattern) {
  604. for (const auto& descriptor : shape.property_table()) {
  605. if (descriptor.key.view().starts_with(property_pattern)) {
  606. Line::CompletionSuggestion completion { descriptor.key };
  607. if (!results.contains_slow(completion)) { // hide duplicates
  608. results.append(completion);
  609. }
  610. }
  611. }
  612. if (const auto* prototype = shape.prototype()) {
  613. list_all_properties(prototype->shape(), property_pattern);
  614. }
  615. };
  616. if (token.contains(".")) {
  617. auto parts = token.split('.', true);
  618. // refuse either `.` or `a.b.c`
  619. if (parts.size() > 2 || parts.size() == 0)
  620. return {};
  621. auto name = parts[0];
  622. auto property_pattern = parts[1];
  623. auto maybe_variable = interpreter->get_variable(name);
  624. if (maybe_variable.is_empty()) {
  625. maybe_variable = interpreter->global_object().get(name);
  626. if (maybe_variable.is_empty())
  627. return {};
  628. }
  629. auto variable = maybe_variable;
  630. if (!variable.is_object())
  631. return {};
  632. const auto* object = variable.to_object(interpreter->heap());
  633. const auto& shape = object->shape();
  634. list_all_properties(shape, property_pattern);
  635. if (results.size())
  636. editor.suggest(property_pattern.length());
  637. return results;
  638. }
  639. const auto& variable = interpreter->global_object();
  640. list_all_properties(variable.shape(), token);
  641. if (results.size())
  642. editor.suggest(token.length());
  643. return results;
  644. };
  645. s_editor->on_tab_complete_first_token = [complete](auto& value) { return complete(value); };
  646. s_editor->on_tab_complete_other_token = [complete](auto& value) { return complete(value); };
  647. repl(*interpreter);
  648. } else {
  649. interpreter = JS::Interpreter::create<JS::GlobalObject>();
  650. ReplConsoleClient console_client(interpreter->console());
  651. interpreter->console().set_client(console_client);
  652. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  653. if (test_mode)
  654. enable_test_mode(*interpreter);
  655. signal(SIGINT, [](int) {
  656. sigint_handler();
  657. });
  658. auto file = Core::File::construct(script_path);
  659. if (!file->open(Core::IODevice::ReadOnly)) {
  660. fprintf(stderr, "Failed to open %s: %s\n", script_path, file->error_string());
  661. return 1;
  662. }
  663. auto file_contents = file->read_all();
  664. StringView source;
  665. if (file_has_shebang(file_contents)) {
  666. source = strip_shebang(file_contents);
  667. } else {
  668. source = file_contents;
  669. }
  670. auto parser = JS::Parser(JS::Lexer(source));
  671. auto program = parser.parse_program();
  672. if (s_dump_ast)
  673. program->dump(0);
  674. if (parser.has_errors()) {
  675. printf("Parse Error\n");
  676. return 1;
  677. }
  678. auto result = interpreter->run(*program);
  679. if (interpreter->exception()) {
  680. printf("Uncaught exception: ");
  681. print(interpreter->exception()->value());
  682. interpreter->clear_exception();
  683. return 1;
  684. }
  685. if (s_print_last_result)
  686. print(result);
  687. }
  688. return 0;
  689. }