js.cpp 25 KB

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