js.cpp 24 KB

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