js.cpp 24 KB

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