js.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  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_without_side_effects().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. bool parse_and_run(JS::Interpreter& interpreter, const StringView& source)
  240. {
  241. auto parser = JS::Parser(JS::Lexer(source));
  242. auto program = parser.parse_program();
  243. if (s_dump_ast)
  244. program->dump(0);
  245. if (parser.has_errors()) {
  246. auto error = parser.errors()[0];
  247. interpreter.throw_exception<JS::SyntaxError>(error.to_string());
  248. } else {
  249. interpreter.run(*program);
  250. }
  251. if (interpreter.exception()) {
  252. printf("Uncaught exception: ");
  253. print(interpreter.exception()->value());
  254. interpreter.clear_exception();
  255. return false;
  256. }
  257. if (s_print_last_result)
  258. print(interpreter.last_value());
  259. return true;
  260. }
  261. ReplObject::ReplObject()
  262. {
  263. }
  264. void ReplObject::initialize()
  265. {
  266. GlobalObject::initialize();
  267. put_native_function("exit", exit_interpreter);
  268. put_native_function("help", repl_help);
  269. put_native_function("load", load_file, 1);
  270. put_native_function("save", save_to_file, 1);
  271. }
  272. ReplObject::~ReplObject()
  273. {
  274. }
  275. JS::Value ReplObject::save_to_file(JS::Interpreter& interpreter)
  276. {
  277. if (!interpreter.argument_count())
  278. return JS::Value(false);
  279. String save_path = interpreter.argument(0).to_string_without_side_effects();
  280. StringView path = StringView(save_path.characters());
  281. if (write_to_file(path)) {
  282. return JS::Value(true);
  283. }
  284. return JS::Value(false);
  285. }
  286. JS::Value ReplObject::exit_interpreter(JS::Interpreter& interpreter)
  287. {
  288. if (!interpreter.argument_count())
  289. exit(0);
  290. auto exit_code = interpreter.argument(0).to_number(interpreter);
  291. if (interpreter.exception())
  292. return {};
  293. exit(exit_code.as_double());
  294. }
  295. JS::Value ReplObject::repl_help(JS::Interpreter&)
  296. {
  297. printf("REPL commands:\n");
  298. printf(" exit(code): exit the REPL with specified code. Defaults to 0.\n");
  299. printf(" help(): display this menu\n");
  300. 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");
  301. return JS::js_undefined();
  302. }
  303. JS::Value ReplObject::load_file(JS::Interpreter& interpreter)
  304. {
  305. if (!interpreter.argument_count())
  306. return JS::Value(false);
  307. for (auto& file : interpreter.call_frame().arguments) {
  308. String file_name = file.as_string().string();
  309. auto js_file = Core::File::construct(file_name);
  310. if (!js_file->open(Core::IODevice::ReadOnly)) {
  311. fprintf(stderr, "Failed to open %s: %s\n", file_name.characters(), js_file->error_string());
  312. }
  313. auto file_contents = js_file->read_all();
  314. StringView source;
  315. if (file_has_shebang(file_contents)) {
  316. source = strip_shebang(file_contents);
  317. } else {
  318. source = file_contents;
  319. }
  320. parse_and_run(interpreter, source);
  321. }
  322. return JS::Value(true);
  323. }
  324. void repl(JS::Interpreter& interpreter)
  325. {
  326. while (true) {
  327. String piece = read_next_piece();
  328. if (piece.is_empty())
  329. continue;
  330. repl_statements.append(piece);
  331. parse_and_run(interpreter, piece);
  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_without_side_effects() : "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_without_side_effects() : "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. s_print_last_result = true;
  439. interpreter = JS::Interpreter::create<ReplObject>();
  440. ReplConsoleClient console_client(interpreter->console());
  441. interpreter->console().set_client(console_client);
  442. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  443. if (test_mode)
  444. enable_test_mode(*interpreter);
  445. s_editor = make<Line::Editor>();
  446. signal(SIGINT, [](int) {
  447. if (!s_editor->is_editing())
  448. sigint_handler();
  449. s_editor->interrupted();
  450. });
  451. signal(SIGWINCH, [](int) {
  452. s_editor->resized();
  453. });
  454. s_editor->on_display_refresh = [syntax_highlight](Line::Editor& editor) {
  455. auto stylize = [&](Line::Span span, Line::Style styles) {
  456. if (syntax_highlight)
  457. editor.stylize(span, styles);
  458. };
  459. editor.strip_styles();
  460. StringBuilder builder;
  461. builder.append(editor.line());
  462. // FIXME: The lexer returns weird position information without this
  463. builder.append(" ");
  464. String str = builder.build();
  465. size_t open_indents = s_repl_line_level;
  466. JS::Lexer lexer(str);
  467. bool indenters_starting_line = true;
  468. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  469. auto length = token.value().length();
  470. auto start = token.line_column() - 2;
  471. auto end = start + length;
  472. if (indenters_starting_line) {
  473. if (token.type() != JS::TokenType::ParenClose && token.type() != JS::TokenType::BracketClose && token.type() != JS::TokenType::CurlyClose) {
  474. indenters_starting_line = false;
  475. } else {
  476. --open_indents;
  477. }
  478. }
  479. switch (token.type()) {
  480. case JS::TokenType::Invalid:
  481. case JS::TokenType::Eof:
  482. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Red), Line::Style::Underline });
  483. break;
  484. case JS::TokenType::NumericLiteral:
  485. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Magenta) });
  486. break;
  487. case JS::TokenType::StringLiteral:
  488. case JS::TokenType::TemplateLiteralStart:
  489. case JS::TokenType::TemplateLiteralEnd:
  490. case JS::TokenType::TemplateLiteralString:
  491. case JS::TokenType::RegexLiteral:
  492. case JS::TokenType::UnterminatedStringLiteral:
  493. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Green), Line::Style::Bold });
  494. break;
  495. case JS::TokenType::BracketClose:
  496. case JS::TokenType::BracketOpen:
  497. case JS::TokenType::Comma:
  498. case JS::TokenType::CurlyClose:
  499. case JS::TokenType::CurlyOpen:
  500. case JS::TokenType::ParenClose:
  501. case JS::TokenType::ParenOpen:
  502. case JS::TokenType::Semicolon:
  503. case JS::TokenType::Period:
  504. break;
  505. case JS::TokenType::Ampersand:
  506. case JS::TokenType::AmpersandEquals:
  507. case JS::TokenType::Asterisk:
  508. case JS::TokenType::DoubleAsteriskEquals:
  509. case JS::TokenType::AsteriskEquals:
  510. case JS::TokenType::Caret:
  511. case JS::TokenType::CaretEquals:
  512. case JS::TokenType::DoubleAmpersand:
  513. case JS::TokenType::DoubleAsterisk:
  514. case JS::TokenType::DoublePipe:
  515. case JS::TokenType::DoubleQuestionMark:
  516. case JS::TokenType::Equals:
  517. case JS::TokenType::EqualsEquals:
  518. case JS::TokenType::EqualsEqualsEquals:
  519. case JS::TokenType::ExclamationMark:
  520. case JS::TokenType::ExclamationMarkEquals:
  521. case JS::TokenType::ExclamationMarkEqualsEquals:
  522. case JS::TokenType::GreaterThan:
  523. case JS::TokenType::GreaterThanEquals:
  524. case JS::TokenType::LessThan:
  525. case JS::TokenType::LessThanEquals:
  526. case JS::TokenType::Minus:
  527. case JS::TokenType::MinusEquals:
  528. case JS::TokenType::MinusMinus:
  529. case JS::TokenType::Percent:
  530. case JS::TokenType::PercentEquals:
  531. case JS::TokenType::Pipe:
  532. case JS::TokenType::PipeEquals:
  533. case JS::TokenType::Plus:
  534. case JS::TokenType::PlusEquals:
  535. case JS::TokenType::PlusPlus:
  536. case JS::TokenType::QuestionMark:
  537. case JS::TokenType::QuestionMarkPeriod:
  538. case JS::TokenType::ShiftLeft:
  539. case JS::TokenType::ShiftLeftEquals:
  540. case JS::TokenType::ShiftRight:
  541. case JS::TokenType::ShiftRightEquals:
  542. case JS::TokenType::Slash:
  543. case JS::TokenType::SlashEquals:
  544. case JS::TokenType::Tilde:
  545. case JS::TokenType::UnsignedShiftRight:
  546. case JS::TokenType::UnsignedShiftRightEquals:
  547. break;
  548. case JS::TokenType::BoolLiteral:
  549. case JS::TokenType::NullLiteral:
  550. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow), Line::Style::Bold });
  551. break;
  552. case JS::TokenType::Class:
  553. case JS::TokenType::Const:
  554. case JS::TokenType::Debugger:
  555. case JS::TokenType::Delete:
  556. case JS::TokenType::Function:
  557. case JS::TokenType::In:
  558. case JS::TokenType::Instanceof:
  559. case JS::TokenType::Interface:
  560. case JS::TokenType::Let:
  561. case JS::TokenType::New:
  562. case JS::TokenType::TemplateLiteralExprStart:
  563. case JS::TokenType::TemplateLiteralExprEnd:
  564. case JS::TokenType::Throw:
  565. case JS::TokenType::Typeof:
  566. case JS::TokenType::Var:
  567. case JS::TokenType::Void:
  568. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Blue), Line::Style::Bold });
  569. break;
  570. case JS::TokenType::Await:
  571. case JS::TokenType::Case:
  572. case JS::TokenType::Catch:
  573. case JS::TokenType::Do:
  574. case JS::TokenType::Else:
  575. case JS::TokenType::Finally:
  576. case JS::TokenType::For:
  577. case JS::TokenType::If:
  578. case JS::TokenType::Return:
  579. case JS::TokenType::Switch:
  580. case JS::TokenType::Try:
  581. case JS::TokenType::While:
  582. case JS::TokenType::Yield:
  583. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan), Line::Style::Italic });
  584. break;
  585. case JS::TokenType::Identifier:
  586. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::White), Line::Style::Bold });
  587. default:
  588. break;
  589. }
  590. }
  591. editor.set_prompt(prompt_for_level(open_indents));
  592. };
  593. auto complete = [&interpreter](const Line::Editor& editor) -> Vector<Line::CompletionSuggestion> {
  594. auto line = editor.line(editor.cursor());
  595. JS::Lexer lexer { line };
  596. enum {
  597. Initial,
  598. CompleteVariable,
  599. CompleteNullProperty,
  600. CompleteProperty,
  601. } mode { Initial };
  602. StringView variable_name;
  603. StringView property_name;
  604. // we're only going to complete either
  605. // - <N>
  606. // where N is part of the name of a variable
  607. // - <N>.<P>
  608. // where N is the complete name of a variable and
  609. // P is part of the name of one of its properties
  610. auto js_token = lexer.next();
  611. for (; js_token.type() != JS::TokenType::Eof; js_token = lexer.next()) {
  612. switch (mode) {
  613. case CompleteVariable:
  614. switch (js_token.type()) {
  615. case JS::TokenType::Period:
  616. // ...<name> <dot>
  617. mode = CompleteNullProperty;
  618. break;
  619. default:
  620. // not a dot, reset back to initial
  621. mode = Initial;
  622. break;
  623. }
  624. break;
  625. case CompleteNullProperty:
  626. if (js_token.is_identifier_name()) {
  627. // ...<name> <dot> <name>
  628. mode = CompleteProperty;
  629. property_name = js_token.value();
  630. } else {
  631. mode = Initial;
  632. }
  633. break;
  634. case CompleteProperty:
  635. // something came after the property access, reset to initial
  636. case Initial:
  637. if (js_token.is_identifier_name()) {
  638. // ...<name>...
  639. mode = CompleteVariable;
  640. variable_name = js_token.value();
  641. } else {
  642. mode = Initial;
  643. }
  644. break;
  645. }
  646. }
  647. bool last_token_has_trivia = js_token.trivia().length() > 0;
  648. if (mode == CompleteNullProperty) {
  649. mode = CompleteProperty;
  650. property_name = "";
  651. last_token_has_trivia = false; // <name> <dot> [tab] is sensible to complete.
  652. }
  653. if (mode == Initial || last_token_has_trivia)
  654. return {}; // we do not know how to complete this
  655. Vector<Line::CompletionSuggestion> results;
  656. Function<void(const JS::Shape&, const StringView&)> list_all_properties = [&results, &list_all_properties](const JS::Shape& shape, auto& property_pattern) {
  657. for (const auto& descriptor : shape.property_table()) {
  658. if (descriptor.key.view().starts_with(property_pattern)) {
  659. Line::CompletionSuggestion completion { descriptor.key };
  660. if (!results.contains_slow(completion)) { // hide duplicates
  661. results.append(completion);
  662. }
  663. }
  664. }
  665. if (const auto* prototype = shape.prototype()) {
  666. list_all_properties(prototype->shape(), property_pattern);
  667. }
  668. };
  669. switch (mode) {
  670. case CompleteProperty: {
  671. auto maybe_variable = interpreter->get_variable(variable_name);
  672. if (maybe_variable.is_empty()) {
  673. maybe_variable = interpreter->global_object().get(variable_name);
  674. if (maybe_variable.is_empty())
  675. break;
  676. }
  677. auto variable = maybe_variable;
  678. if (!variable.is_object())
  679. break;
  680. const auto* object = variable.to_object(*interpreter);
  681. const auto& shape = object->shape();
  682. list_all_properties(shape, property_name);
  683. if (results.size())
  684. editor.suggest(property_name.length());
  685. break;
  686. }
  687. case CompleteVariable: {
  688. const auto& variable = interpreter->global_object();
  689. list_all_properties(variable.shape(), variable_name);
  690. if (results.size())
  691. editor.suggest(variable_name.length());
  692. break;
  693. }
  694. default:
  695. ASSERT_NOT_REACHED();
  696. }
  697. return results;
  698. };
  699. s_editor->on_tab_complete = move(complete);
  700. repl(*interpreter);
  701. } else {
  702. interpreter = JS::Interpreter::create<JS::GlobalObject>();
  703. ReplConsoleClient console_client(interpreter->console());
  704. interpreter->console().set_client(console_client);
  705. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  706. if (test_mode)
  707. enable_test_mode(*interpreter);
  708. signal(SIGINT, [](int) {
  709. sigint_handler();
  710. });
  711. auto file = Core::File::construct(script_path);
  712. if (!file->open(Core::IODevice::ReadOnly)) {
  713. fprintf(stderr, "Failed to open %s: %s\n", script_path, file->error_string());
  714. return 1;
  715. }
  716. auto file_contents = file->read_all();
  717. StringView source;
  718. if (file_has_shebang(file_contents)) {
  719. source = strip_shebang(file_contents);
  720. } else {
  721. source = file_contents;
  722. }
  723. if (!parse_and_run(*interpreter, source))
  724. return 1;
  725. }
  726. return 0;
  727. }