js.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  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[31;1m");
  176. else if (value.is_number())
  177. printf("\033[35;1m");
  178. else if (value.is_boolean())
  179. printf("\033[32;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& interpreter)
  267. {
  268. StringBuilder help_text;
  269. help_text.append("REPL commands:\n");
  270. help_text.append(" exit(code): exit the REPL with specified code. Defaults to 0.\n");
  271. help_text.append(" help(): display this menu\n");
  272. 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");
  273. String result = help_text.to_string();
  274. return js_string(interpreter, result);
  275. }
  276. JS::Value ReplObject::load_file(JS::Interpreter& interpreter)
  277. {
  278. if (!interpreter.argument_count())
  279. return JS::Value(false);
  280. for (auto& file : interpreter.call_frame().arguments) {
  281. String file_name = file.as_string()->string();
  282. auto js_file = Core::File::construct(file_name);
  283. if (!js_file->open(Core::IODevice::ReadOnly)) {
  284. fprintf(stderr, "Failed to open %s: %s\n", file_name.characters(), js_file->error_string());
  285. }
  286. auto file_contents = js_file->read_all();
  287. StringView source;
  288. if (file_has_shebang(file_contents)) {
  289. source = strip_shebang(file_contents);
  290. } else {
  291. source = file_contents;
  292. }
  293. auto parser = JS::Parser(JS::Lexer(source));
  294. auto program = parser.parse_program();
  295. if (dump_ast)
  296. program->dump(0);
  297. if (parser.has_errors())
  298. continue;
  299. interpreter.run(*program);
  300. if (print_last_result)
  301. print(interpreter.last_value());
  302. }
  303. return JS::Value(true);
  304. }
  305. void repl(JS::Interpreter& interpreter)
  306. {
  307. while (true) {
  308. String piece = read_next_piece();
  309. if (piece.is_empty())
  310. continue;
  311. repl_statements.append(piece);
  312. auto parser = JS::Parser(JS::Lexer(piece));
  313. auto program = parser.parse_program();
  314. if (dump_ast)
  315. program->dump(0);
  316. if (parser.has_errors()) {
  317. printf("Parse error\n");
  318. continue;
  319. }
  320. interpreter.run(*program);
  321. if (interpreter.exception()) {
  322. printf("Uncaught exception: ");
  323. print(interpreter.exception()->value());
  324. interpreter.clear_exception();
  325. } else {
  326. print(interpreter.last_value());
  327. }
  328. }
  329. }
  330. JS::Value assert_impl(JS::Interpreter& interpreter)
  331. {
  332. if (!interpreter.argument_count())
  333. return interpreter.throw_exception<JS::TypeError>("No arguments specified");
  334. auto assertion_value = interpreter.argument(0).to_boolean();
  335. if (!assertion_value)
  336. return interpreter.throw_exception<JS::Error>("AssertionError", "The assertion failed!");
  337. return JS::Value(assertion_value);
  338. }
  339. JS::Value assert_not_reached(JS::Interpreter& interpreter)
  340. {
  341. return interpreter.throw_exception<JS::Error>("AssertionError", "assertNotReached() was reached!");
  342. }
  343. void enable_test_mode(JS::Interpreter& interpreter)
  344. {
  345. interpreter.global_object().put_native_function("load", ReplObject::load_file);
  346. interpreter.global_object().put_native_function("assert", assert_impl);
  347. interpreter.global_object().put_native_function("assertNotReached", assert_not_reached);
  348. }
  349. int main(int argc, char** argv)
  350. {
  351. bool gc_on_every_allocation = false;
  352. bool syntax_highlight = false;
  353. bool test_mode = false;
  354. const char* script_path = nullptr;
  355. Core::ArgsParser args_parser;
  356. args_parser.add_option(dump_ast, "Dump the AST", "dump-ast", 'A');
  357. args_parser.add_option(print_last_result, "Print last result", "print-last-result", 'l');
  358. args_parser.add_option(gc_on_every_allocation, "GC on every allocation", "gc-on-every-allocation", 'g');
  359. args_parser.add_option(syntax_highlight, "Enable live syntax highlighting", "syntax-highlight", 's');
  360. args_parser.add_option(test_mode, "Run the interpreter with added functionality for the test harness", "test-mode", 't');
  361. args_parser.add_positional_argument(script_path, "Path to script file", "script", Core::ArgsParser::Required::No);
  362. args_parser.parse(argc, argv);
  363. if (script_path == nullptr) {
  364. auto interpreter = JS::Interpreter::create<ReplObject>();
  365. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  366. if (test_mode)
  367. enable_test_mode(*interpreter);
  368. editor = make<Line::Editor>();
  369. signal(SIGINT, [](int) {
  370. editor->interrupted();
  371. });
  372. signal(SIGWINCH, [](int) {
  373. editor->resized();
  374. });
  375. editor->initialize();
  376. editor->on_display_refresh = [syntax_highlight](Line::Editor& editor) {
  377. auto stylize = [&](Line::Span span, Line::Style styles) {
  378. if (syntax_highlight)
  379. editor.stylize(span, styles);
  380. };
  381. editor.strip_styles();
  382. StringBuilder builder;
  383. builder.append({ editor.buffer().data(), editor.buffer().size() });
  384. // FIXME: The lexer returns weird position information without this
  385. builder.append(" ");
  386. String str = builder.build();
  387. size_t open_indents = repl_line_level;
  388. JS::Lexer lexer(str, false);
  389. bool indenters_starting_line = true;
  390. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  391. auto length = token.value().length();
  392. auto start = token.line_column() - 2;
  393. auto end = start + length;
  394. if (indenters_starting_line) {
  395. if (token.type() != JS::TokenType::ParenClose && token.type() != JS::TokenType::BracketClose && token.type() != JS::TokenType::CurlyClose) {
  396. indenters_starting_line = false;
  397. } else {
  398. --open_indents;
  399. }
  400. }
  401. switch (token.type()) {
  402. case JS::TokenType::Invalid:
  403. case JS::TokenType::Eof:
  404. stylize({ start, end }, { Line::Style::Foreground(Line::Style::Color::Red), Line::Style::Underline });
  405. break;
  406. case JS::TokenType::NumericLiteral:
  407. stylize({ start, end }, { Line::Style::Foreground(Line::Style::Color::Magenta) });
  408. break;
  409. case JS::TokenType::StringLiteral:
  410. case JS::TokenType::RegexLiteral:
  411. case JS::TokenType::UnterminatedStringLiteral:
  412. stylize({ start, end }, { Line::Style::Foreground(Line::Style::Color::Red) });
  413. break;
  414. case JS::TokenType::BracketClose:
  415. case JS::TokenType::BracketOpen:
  416. case JS::TokenType::Caret:
  417. case JS::TokenType::Comma:
  418. case JS::TokenType::CurlyClose:
  419. case JS::TokenType::CurlyOpen:
  420. case JS::TokenType::ParenClose:
  421. case JS::TokenType::ParenOpen:
  422. case JS::TokenType::Semicolon:
  423. case JS::TokenType::Period:
  424. break;
  425. case JS::TokenType::Ampersand:
  426. case JS::TokenType::AmpersandEquals:
  427. case JS::TokenType::Asterisk:
  428. case JS::TokenType::AsteriskAsteriskEquals:
  429. case JS::TokenType::AsteriskEquals:
  430. case JS::TokenType::DoubleAmpersand:
  431. case JS::TokenType::DoubleAsterisk:
  432. case JS::TokenType::DoublePipe:
  433. case JS::TokenType::DoubleQuestionMark:
  434. case JS::TokenType::Equals:
  435. case JS::TokenType::EqualsEquals:
  436. case JS::TokenType::EqualsEqualsEquals:
  437. case JS::TokenType::ExclamationMark:
  438. case JS::TokenType::ExclamationMarkEquals:
  439. case JS::TokenType::ExclamationMarkEqualsEquals:
  440. case JS::TokenType::GreaterThan:
  441. case JS::TokenType::GreaterThanEquals:
  442. case JS::TokenType::LessThan:
  443. case JS::TokenType::LessThanEquals:
  444. case JS::TokenType::Minus:
  445. case JS::TokenType::MinusEquals:
  446. case JS::TokenType::MinusMinus:
  447. case JS::TokenType::Percent:
  448. case JS::TokenType::PercentEquals:
  449. case JS::TokenType::Pipe:
  450. case JS::TokenType::PipeEquals:
  451. case JS::TokenType::Plus:
  452. case JS::TokenType::PlusEquals:
  453. case JS::TokenType::PlusPlus:
  454. case JS::TokenType::QuestionMark:
  455. case JS::TokenType::QuestionMarkPeriod:
  456. case JS::TokenType::ShiftLeft:
  457. case JS::TokenType::ShiftLeftEquals:
  458. case JS::TokenType::ShiftRight:
  459. case JS::TokenType::ShiftRightEquals:
  460. case JS::TokenType::Slash:
  461. case JS::TokenType::SlashEquals:
  462. case JS::TokenType::Tilde:
  463. case JS::TokenType::UnsignedShiftRight:
  464. case JS::TokenType::UnsignedShiftRightEquals:
  465. stylize({ start, end }, { Line::Style::Foreground(Line::Style::Color::Magenta) });
  466. break;
  467. case JS::TokenType::NullLiteral:
  468. stylize({ start, end }, { Line::Style::Foreground(Line::Style::Color::Yellow), Line::Style::Bold });
  469. break;
  470. case JS::TokenType::BoolLiteral:
  471. stylize({ start, end }, { Line::Style::Foreground(Line::Style::Color::Green), Line::Style::Bold });
  472. break;
  473. case JS::TokenType::Class:
  474. case JS::TokenType::Const:
  475. case JS::TokenType::Delete:
  476. case JS::TokenType::Function:
  477. case JS::TokenType::In:
  478. case JS::TokenType::Instanceof:
  479. case JS::TokenType::Interface:
  480. case JS::TokenType::Let:
  481. case JS::TokenType::New:
  482. case JS::TokenType::Throw:
  483. case JS::TokenType::Typeof:
  484. case JS::TokenType::Var:
  485. case JS::TokenType::Void:
  486. stylize({ start, end }, { Line::Style::Foreground(Line::Style::Color::Blue), Line::Style::Bold });
  487. break;
  488. case JS::TokenType::Await:
  489. case JS::TokenType::Case:
  490. case JS::TokenType::Catch:
  491. case JS::TokenType::Do:
  492. case JS::TokenType::Else:
  493. case JS::TokenType::Finally:
  494. case JS::TokenType::For:
  495. case JS::TokenType::If:
  496. case JS::TokenType::Return:
  497. case JS::TokenType::Switch:
  498. case JS::TokenType::Try:
  499. case JS::TokenType::While:
  500. case JS::TokenType::Yield:
  501. stylize({ start, end }, { Line::Style::Foreground(Line::Style::Color::Cyan), Line::Style::Italic });
  502. break;
  503. case JS::TokenType::Identifier:
  504. default:
  505. break;
  506. }
  507. }
  508. editor.set_prompt(prompt_for_level(open_indents));
  509. };
  510. auto complete = [&interpreter, &editor = *editor](const String& token) -> Vector<String> {
  511. if (token.length() == 0)
  512. return {}; // nyeh
  513. StringView line { editor.buffer().data(), editor.cursor() };
  514. // we're only going to complete either
  515. // - <N>
  516. // where N is part of the name of a variable
  517. // - <N>.<P>
  518. // where N is the complete name of a variable and
  519. // P is part of the name of one of its properties
  520. Vector<String> results;
  521. Function<void(const JS::Shape&, const StringView&)> list_all_properties = [&results, &list_all_properties](const JS::Shape& shape, auto& property_pattern) {
  522. for (const auto& descriptor : shape.property_table()) {
  523. if (descriptor.value.attributes & JS::Attribute::Enumerable) {
  524. if (descriptor.key.view().starts_with(property_pattern)) {
  525. auto completion = descriptor.key;
  526. if (!results.contains_slow(completion)) { // hide duplicates
  527. results.append(completion);
  528. }
  529. }
  530. }
  531. }
  532. if (const auto* prototype = shape.prototype()) {
  533. list_all_properties(prototype->shape(), property_pattern);
  534. }
  535. };
  536. if (token.contains(".")) {
  537. auto parts = token.split('.', true);
  538. // refuse either `.` or `a.b.c`
  539. if (parts.size() > 2 || parts.size() == 0)
  540. return {};
  541. auto name = parts[0];
  542. auto property_pattern = parts[1];
  543. auto maybe_variable = interpreter->get_variable(name);
  544. if (!maybe_variable.has_value()) {
  545. maybe_variable = interpreter->global_object().get(name);
  546. if (!maybe_variable.has_value())
  547. return {};
  548. }
  549. const auto& variable = maybe_variable.value();
  550. if (!variable.is_object())
  551. return {};
  552. const auto* object = variable.to_object(interpreter->heap());
  553. const auto& shape = object->shape();
  554. list_all_properties(shape, property_pattern);
  555. if (results.size())
  556. editor.suggest(property_pattern.length());
  557. return results;
  558. }
  559. const auto& variable = interpreter->global_object();
  560. list_all_properties(variable.shape(), token);
  561. if (results.size())
  562. editor.suggest(token.length());
  563. return results;
  564. };
  565. editor->on_tab_complete_first_token = [complete](auto& value) { return complete(value); };
  566. editor->on_tab_complete_other_token = [complete](auto& value) { return complete(value); };
  567. repl(*interpreter);
  568. } else {
  569. auto interpreter = JS::Interpreter::create<JS::GlobalObject>();
  570. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  571. if (test_mode)
  572. enable_test_mode(*interpreter);
  573. auto file = Core::File::construct(script_path);
  574. if (!file->open(Core::IODevice::ReadOnly)) {
  575. fprintf(stderr, "Failed to open %s: %s\n", script_path, file->error_string());
  576. return 1;
  577. }
  578. auto file_contents = file->read_all();
  579. StringView source;
  580. if (file_has_shebang(file_contents)) {
  581. source = strip_shebang(file_contents);
  582. } else {
  583. source = file_contents;
  584. }
  585. auto parser = JS::Parser(JS::Lexer(source));
  586. auto program = parser.parse_program();
  587. if (dump_ast)
  588. program->dump(0);
  589. if (parser.has_errors()) {
  590. printf("Parse Error\n");
  591. return 1;
  592. }
  593. auto result = interpreter->run(*program);
  594. if (interpreter->exception()) {
  595. printf("Uncaught exception: ");
  596. print(interpreter->exception()->value());
  597. interpreter->clear_exception();
  598. return 1;
  599. }
  600. if (print_last_result)
  601. print(result);
  602. }
  603. return 0;
  604. }