js.cpp 29 KB

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