js.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  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. bool dump_ast = false;
  60. bool print_last_result = false;
  61. static OwnPtr<Line::Editor> editor;
  62. static int 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 = editor->get_line(prompt_for_level(repl_line_level));
  77. 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. repl_line_level++;
  86. break;
  87. case JS::TokenType::BracketClose:
  88. case JS::TokenType::CurlyClose:
  89. case JS::TokenType::ParenClose:
  90. repl_line_level--;
  91. break;
  92. default:
  93. break;
  94. }
  95. }
  96. } while (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()) {
  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 (dump_ast)
  299. program->dump(0);
  300. if (parser.has_errors())
  301. continue;
  302. interpreter.run(*program);
  303. if (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 (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. int main(int argc, char** argv)
  338. {
  339. bool gc_on_every_allocation = false;
  340. bool syntax_highlight = false;
  341. bool test_mode = false;
  342. const char* script_path = nullptr;
  343. Core::ArgsParser args_parser;
  344. args_parser.add_option(dump_ast, "Dump the AST", "dump-ast", 'A');
  345. args_parser.add_option(print_last_result, "Print last result", "print-last-result", 'l');
  346. args_parser.add_option(gc_on_every_allocation, "GC on every allocation", "gc-on-every-allocation", 'g');
  347. args_parser.add_option(syntax_highlight, "Enable live syntax highlighting", "syntax-highlight", 's');
  348. args_parser.add_option(test_mode, "Run the interpreter with added functionality for the test harness", "test-mode", 't');
  349. args_parser.add_positional_argument(script_path, "Path to script file", "script", Core::ArgsParser::Required::No);
  350. args_parser.parse(argc, argv);
  351. if (script_path == nullptr) {
  352. auto interpreter = JS::Interpreter::create<ReplObject>();
  353. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  354. if (test_mode)
  355. enable_test_mode(*interpreter);
  356. editor = make<Line::Editor>();
  357. signal(SIGINT, [](int) {
  358. editor->interrupted();
  359. });
  360. signal(SIGWINCH, [](int) {
  361. editor->resized();
  362. });
  363. editor->initialize();
  364. editor->on_display_refresh = [syntax_highlight](Line::Editor& editor) {
  365. auto stylize = [&](Line::Span span, Line::Style styles) {
  366. if (syntax_highlight)
  367. editor.stylize(span, styles);
  368. };
  369. editor.strip_styles();
  370. StringBuilder builder;
  371. builder.append({ editor.buffer().data(), editor.buffer().size() });
  372. // FIXME: The lexer returns weird position information without this
  373. builder.append(" ");
  374. String str = builder.build();
  375. size_t open_indents = repl_line_level;
  376. JS::Lexer lexer(str, false);
  377. bool indenters_starting_line = true;
  378. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  379. auto length = token.value().length();
  380. auto start = token.line_column() - 2;
  381. auto end = start + length;
  382. if (indenters_starting_line) {
  383. if (token.type() != JS::TokenType::ParenClose && token.type() != JS::TokenType::BracketClose && token.type() != JS::TokenType::CurlyClose) {
  384. indenters_starting_line = false;
  385. } else {
  386. --open_indents;
  387. }
  388. }
  389. switch (token.type()) {
  390. case JS::TokenType::Invalid:
  391. case JS::TokenType::Eof:
  392. stylize({ start, end }, { Line::Style::Foreground(Line::Style::Color::Red), Line::Style::Underline });
  393. break;
  394. case JS::TokenType::NumericLiteral:
  395. stylize({ start, end }, { Line::Style::Foreground(Line::Style::Color::Magenta) });
  396. break;
  397. case JS::TokenType::StringLiteral:
  398. case JS::TokenType::TemplateLiteral:
  399. case JS::TokenType::RegexLiteral:
  400. case JS::TokenType::UnterminatedStringLiteral:
  401. stylize({ start, end }, { Line::Style::Foreground(Line::Style::Color::Green), Line::Style::Bold });
  402. break;
  403. case JS::TokenType::BracketClose:
  404. case JS::TokenType::BracketOpen:
  405. case JS::TokenType::Caret:
  406. case JS::TokenType::Comma:
  407. case JS::TokenType::CurlyClose:
  408. case JS::TokenType::CurlyOpen:
  409. case JS::TokenType::ParenClose:
  410. case JS::TokenType::ParenOpen:
  411. case JS::TokenType::Semicolon:
  412. case JS::TokenType::Period:
  413. break;
  414. case JS::TokenType::Ampersand:
  415. case JS::TokenType::AmpersandEquals:
  416. case JS::TokenType::Asterisk:
  417. case JS::TokenType::AsteriskAsteriskEquals:
  418. case JS::TokenType::AsteriskEquals:
  419. case JS::TokenType::DoubleAmpersand:
  420. case JS::TokenType::DoubleAsterisk:
  421. case JS::TokenType::DoublePipe:
  422. case JS::TokenType::DoubleQuestionMark:
  423. case JS::TokenType::Equals:
  424. case JS::TokenType::EqualsEquals:
  425. case JS::TokenType::EqualsEqualsEquals:
  426. case JS::TokenType::ExclamationMark:
  427. case JS::TokenType::ExclamationMarkEquals:
  428. case JS::TokenType::ExclamationMarkEqualsEquals:
  429. case JS::TokenType::GreaterThan:
  430. case JS::TokenType::GreaterThanEquals:
  431. case JS::TokenType::LessThan:
  432. case JS::TokenType::LessThanEquals:
  433. case JS::TokenType::Minus:
  434. case JS::TokenType::MinusEquals:
  435. case JS::TokenType::MinusMinus:
  436. case JS::TokenType::Percent:
  437. case JS::TokenType::PercentEquals:
  438. case JS::TokenType::Pipe:
  439. case JS::TokenType::PipeEquals:
  440. case JS::TokenType::Plus:
  441. case JS::TokenType::PlusEquals:
  442. case JS::TokenType::PlusPlus:
  443. case JS::TokenType::QuestionMark:
  444. case JS::TokenType::QuestionMarkPeriod:
  445. case JS::TokenType::ShiftLeft:
  446. case JS::TokenType::ShiftLeftEquals:
  447. case JS::TokenType::ShiftRight:
  448. case JS::TokenType::ShiftRightEquals:
  449. case JS::TokenType::Slash:
  450. case JS::TokenType::SlashEquals:
  451. case JS::TokenType::Tilde:
  452. case JS::TokenType::UnsignedShiftRight:
  453. case JS::TokenType::UnsignedShiftRightEquals:
  454. break;
  455. case JS::TokenType::BoolLiteral:
  456. case JS::TokenType::NullLiteral:
  457. stylize({ start, end }, { Line::Style::Foreground(Line::Style::Color::Yellow), Line::Style::Bold });
  458. break;
  459. case JS::TokenType::Class:
  460. case JS::TokenType::Const:
  461. case JS::TokenType::Delete:
  462. case JS::TokenType::Function:
  463. case JS::TokenType::In:
  464. case JS::TokenType::Instanceof:
  465. case JS::TokenType::Interface:
  466. case JS::TokenType::Let:
  467. case JS::TokenType::New:
  468. case JS::TokenType::Throw:
  469. case JS::TokenType::Typeof:
  470. case JS::TokenType::Var:
  471. case JS::TokenType::Void:
  472. stylize({ start, end }, { Line::Style::Foreground(Line::Style::Color::Blue), Line::Style::Bold });
  473. break;
  474. case JS::TokenType::Await:
  475. case JS::TokenType::Case:
  476. case JS::TokenType::Catch:
  477. case JS::TokenType::Do:
  478. case JS::TokenType::Else:
  479. case JS::TokenType::Finally:
  480. case JS::TokenType::For:
  481. case JS::TokenType::If:
  482. case JS::TokenType::Return:
  483. case JS::TokenType::Switch:
  484. case JS::TokenType::Try:
  485. case JS::TokenType::While:
  486. case JS::TokenType::Yield:
  487. stylize({ start, end }, { Line::Style::Foreground(Line::Style::Color::Cyan), Line::Style::Italic });
  488. break;
  489. case JS::TokenType::Identifier:
  490. stylize({ start, end }, { Line::Style::Foreground(Line::Style::Color::White), Line::Style::Bold });
  491. default:
  492. break;
  493. }
  494. }
  495. editor.set_prompt(prompt_for_level(open_indents));
  496. };
  497. auto complete = [&interpreter, &editor = *editor](const String& token) -> Vector<Line::CompletionSuggestion> {
  498. if (token.length() == 0)
  499. return {}; // nyeh
  500. StringView line { editor.buffer().data(), editor.cursor() };
  501. // we're only going to complete either
  502. // - <N>
  503. // where N is part of the name of a variable
  504. // - <N>.<P>
  505. // where N is the complete name of a variable and
  506. // P is part of the name of one of its properties
  507. Vector<Line::CompletionSuggestion> results;
  508. Function<void(const JS::Shape&, const StringView&)> list_all_properties = [&results, &list_all_properties](const JS::Shape& shape, auto& property_pattern) {
  509. for (const auto& descriptor : shape.property_table()) {
  510. if (descriptor.value.attributes & JS::Attribute::Enumerable) {
  511. if (descriptor.key.view().starts_with(property_pattern)) {
  512. Line::CompletionSuggestion completion { descriptor.key };
  513. if (!results.contains_slow(completion)) { // hide duplicates
  514. results.append(completion);
  515. }
  516. }
  517. }
  518. }
  519. if (const auto* prototype = shape.prototype()) {
  520. list_all_properties(prototype->shape(), property_pattern);
  521. }
  522. };
  523. if (token.contains(".")) {
  524. auto parts = token.split('.', true);
  525. // refuse either `.` or `a.b.c`
  526. if (parts.size() > 2 || parts.size() == 0)
  527. return {};
  528. auto name = parts[0];
  529. auto property_pattern = parts[1];
  530. auto maybe_variable = interpreter->get_variable(name);
  531. if (!maybe_variable.has_value()) {
  532. maybe_variable = interpreter->global_object().get(name);
  533. if (!maybe_variable.has_value())
  534. return {};
  535. }
  536. const auto& variable = maybe_variable.value();
  537. if (!variable.is_object())
  538. return {};
  539. const auto* object = variable.to_object(interpreter->heap());
  540. const auto& shape = object->shape();
  541. list_all_properties(shape, property_pattern);
  542. if (results.size())
  543. editor.suggest(property_pattern.length());
  544. return results;
  545. }
  546. const auto& variable = interpreter->global_object();
  547. list_all_properties(variable.shape(), token);
  548. if (results.size())
  549. editor.suggest(token.length());
  550. return results;
  551. };
  552. editor->on_tab_complete_first_token = [complete](auto& value) { return complete(value); };
  553. editor->on_tab_complete_other_token = [complete](auto& value) { return complete(value); };
  554. repl(*interpreter);
  555. } else {
  556. auto interpreter = JS::Interpreter::create<JS::GlobalObject>();
  557. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  558. if (test_mode)
  559. enable_test_mode(*interpreter);
  560. auto file = Core::File::construct(script_path);
  561. if (!file->open(Core::IODevice::ReadOnly)) {
  562. fprintf(stderr, "Failed to open %s: %s\n", script_path, file->error_string());
  563. return 1;
  564. }
  565. auto file_contents = file->read_all();
  566. StringView source;
  567. if (file_has_shebang(file_contents)) {
  568. source = strip_shebang(file_contents);
  569. } else {
  570. source = file_contents;
  571. }
  572. auto parser = JS::Parser(JS::Lexer(source));
  573. auto program = parser.parse_program();
  574. if (dump_ast)
  575. program->dump(0);
  576. if (parser.has_errors()) {
  577. printf("Parse Error\n");
  578. return 1;
  579. }
  580. auto result = interpreter->run(*program);
  581. if (interpreter->exception()) {
  582. printf("Uncaught exception: ");
  583. print(interpreter->exception()->value());
  584. interpreter->clear_exception();
  585. return 1;
  586. }
  587. if (print_last_result)
  588. print(result);
  589. }
  590. return 0;
  591. }