js.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  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/Format.h>
  28. #include <AK/NonnullOwnPtr.h>
  29. #include <AK/StringBuilder.h>
  30. #include <LibCore/ArgsParser.h>
  31. #include <LibCore/File.h>
  32. #include <LibCore/StandardPaths.h>
  33. #include <LibJS/AST.h>
  34. #include <LibJS/Console.h>
  35. #include <LibJS/Interpreter.h>
  36. #include <LibJS/Parser.h>
  37. #include <LibJS/Runtime/Array.h>
  38. #include <LibJS/Runtime/Date.h>
  39. #include <LibJS/Runtime/Error.h>
  40. #include <LibJS/Runtime/Function.h>
  41. #include <LibJS/Runtime/GlobalObject.h>
  42. #include <LibJS/Runtime/Object.h>
  43. #include <LibJS/Runtime/PrimitiveString.h>
  44. #include <LibJS/Runtime/RegExpObject.h>
  45. #include <LibJS/Runtime/Shape.h>
  46. #include <LibJS/Runtime/Value.h>
  47. #include <LibLine/Editor.h>
  48. #include <signal.h>
  49. #include <stdio.h>
  50. RefPtr<JS::VM> vm;
  51. Vector<String> repl_statements;
  52. class ReplObject : public JS::GlobalObject {
  53. public:
  54. ReplObject();
  55. virtual void initialize() override;
  56. virtual ~ReplObject() override;
  57. private:
  58. virtual const char* class_name() const override { return "ReplObject"; }
  59. JS_DECLARE_NATIVE_FUNCTION(exit_interpreter);
  60. JS_DECLARE_NATIVE_FUNCTION(repl_help);
  61. JS_DECLARE_NATIVE_FUNCTION(load_file);
  62. JS_DECLARE_NATIVE_FUNCTION(save_to_file);
  63. };
  64. static bool s_dump_ast = false;
  65. static bool s_print_last_result = false;
  66. static RefPtr<Line::Editor> s_editor;
  67. static String s_history_path = String::formatted("{}/.js-history", Core::StandardPaths::home_directory());
  68. static int s_repl_line_level = 0;
  69. static bool s_fail_repl = false;
  70. static String prompt_for_level(int level)
  71. {
  72. static StringBuilder prompt_builder;
  73. prompt_builder.clear();
  74. prompt_builder.append("> ");
  75. for (auto i = 0; i < level; ++i)
  76. prompt_builder.append(" ");
  77. return prompt_builder.build();
  78. }
  79. static String read_next_piece()
  80. {
  81. StringBuilder piece;
  82. auto line_level_delta_for_next_line { 0 };
  83. do {
  84. auto line_result = s_editor->get_line(prompt_for_level(s_repl_line_level));
  85. line_level_delta_for_next_line = 0;
  86. if (line_result.is_error()) {
  87. s_fail_repl = true;
  88. return "";
  89. }
  90. auto& line = line_result.value();
  91. s_editor->add_to_history(line);
  92. piece.append(line);
  93. auto lexer = JS::Lexer(line);
  94. enum {
  95. NotInLabelOrObjectKey,
  96. InLabelOrObjectKeyIdentifier,
  97. InLabelOrObjectKey
  98. } label_state { NotInLabelOrObjectKey };
  99. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  100. switch (token.type()) {
  101. case JS::TokenType::BracketOpen:
  102. case JS::TokenType::CurlyOpen:
  103. case JS::TokenType::ParenOpen:
  104. label_state = NotInLabelOrObjectKey;
  105. s_repl_line_level++;
  106. break;
  107. case JS::TokenType::BracketClose:
  108. case JS::TokenType::CurlyClose:
  109. case JS::TokenType::ParenClose:
  110. label_state = NotInLabelOrObjectKey;
  111. s_repl_line_level--;
  112. break;
  113. case JS::TokenType::Identifier:
  114. case JS::TokenType::StringLiteral:
  115. if (label_state == NotInLabelOrObjectKey)
  116. label_state = InLabelOrObjectKeyIdentifier;
  117. else
  118. label_state = NotInLabelOrObjectKey;
  119. break;
  120. case JS::TokenType::Colon:
  121. if (label_state == InLabelOrObjectKeyIdentifier)
  122. label_state = InLabelOrObjectKey;
  123. else
  124. label_state = NotInLabelOrObjectKey;
  125. break;
  126. default:
  127. break;
  128. }
  129. }
  130. if (label_state == InLabelOrObjectKey) {
  131. // If there's a label or object literal key at the end of this line,
  132. // prompt for more lines but do not change the line level.
  133. line_level_delta_for_next_line += 1;
  134. }
  135. } while (s_repl_line_level + line_level_delta_for_next_line > 0);
  136. return piece.to_string();
  137. }
  138. static void print_value(JS::Value value, HashTable<JS::Object*>& seen_objects);
  139. static void print_array(JS::Array& array, HashTable<JS::Object*>& seen_objects)
  140. {
  141. bool first = true;
  142. out("[ ");
  143. for (auto it = array.indexed_properties().begin(false); it != array.indexed_properties().end(); ++it) {
  144. if (!first)
  145. out(", ");
  146. first = false;
  147. auto value = it.value_and_attributes(&array).value;
  148. // The V8 repl doesn't throw an exception here, and instead just
  149. // prints 'undefined'. We may choose to replicate that behavior in
  150. // the future, but for now lets just catch the error
  151. if (vm->exception())
  152. return;
  153. print_value(value, seen_objects);
  154. }
  155. out(" ]");
  156. }
  157. static void print_object(JS::Object& object, HashTable<JS::Object*>& seen_objects)
  158. {
  159. out("{{ ");
  160. bool first = true;
  161. for (auto& entry : object.indexed_properties()) {
  162. if (!first)
  163. out(", ");
  164. first = false;
  165. out("\"\033[33;1m{}\033[0m\": ", entry.index());
  166. auto value = entry.value_and_attributes(&object).value;
  167. // The V8 repl doesn't throw an exception here, and instead just
  168. // prints 'undefined'. We may choose to replicate that behavior in
  169. // the future, but for now lets just catch the error
  170. if (vm->exception())
  171. return;
  172. print_value(value, seen_objects);
  173. }
  174. if (!object.indexed_properties().is_empty() && object.shape().property_count())
  175. out(", ");
  176. size_t index = 0;
  177. for (auto& it : object.shape().property_table_ordered()) {
  178. if (it.key.is_string()) {
  179. out("\"\033[33;1m{}\033[0m\": ", it.key.to_display_string());
  180. } else {
  181. out("\033[33;1m{}\033[0m: ", it.key.to_display_string());
  182. }
  183. print_value(object.get_direct(it.value.offset), seen_objects);
  184. if (index != object.shape().property_count() - 1)
  185. out(", ");
  186. ++index;
  187. }
  188. out(" }}");
  189. }
  190. static void print_function(const JS::Object& function, HashTable<JS::Object*>&)
  191. {
  192. out("\033[34;1m[{}]\033[0m", function.class_name());
  193. }
  194. static void print_date(const JS::Object& date, HashTable<JS::Object*>&)
  195. {
  196. out("\033[34;1mDate {}\033[0m", static_cast<const JS::Date&>(date).string());
  197. }
  198. static void print_error(const JS::Object& object, HashTable<JS::Object*>&)
  199. {
  200. auto& error = static_cast<const JS::Error&>(object);
  201. out("\033[34;1m[{}]\033[0m", error.name());
  202. if (!error.message().is_empty())
  203. out(": {}", error.message());
  204. }
  205. static void print_regexp(const JS::Object& object, HashTable<JS::Object*>&)
  206. {
  207. auto& regexp = static_cast<const JS::RegExpObject&>(object);
  208. out("\033[34;1m/{}/{}\033[0m", regexp.pattern(), regexp.flags());
  209. }
  210. static void print_value(JS::Value value, HashTable<JS::Object*>& seen_objects)
  211. {
  212. if (value.is_empty()) {
  213. out("\033[34;1m<empty>\033[0m");
  214. return;
  215. }
  216. if (value.is_object()) {
  217. if (seen_objects.contains(&value.as_object())) {
  218. // FIXME: Maybe we should only do this for circular references,
  219. // not for all reoccurring objects.
  220. out("<already printed Object {}>", &value.as_object());
  221. return;
  222. }
  223. seen_objects.set(&value.as_object());
  224. }
  225. if (value.is_array())
  226. return print_array(static_cast<JS::Array&>(value.as_object()), seen_objects);
  227. if (value.is_object()) {
  228. auto& object = value.as_object();
  229. if (object.is_function())
  230. return print_function(object, seen_objects);
  231. if (object.is_date())
  232. return print_date(object, seen_objects);
  233. if (object.is_error())
  234. return print_error(object, seen_objects);
  235. if (object.is_regexp_object())
  236. return print_regexp(object, seen_objects);
  237. return print_object(object, seen_objects);
  238. }
  239. if (value.is_string())
  240. out("\033[32;1m");
  241. else if (value.is_number() || value.is_bigint())
  242. out("\033[35;1m");
  243. else if (value.is_boolean())
  244. out("\033[33;1m");
  245. else if (value.is_null())
  246. out("\033[33;1m");
  247. else if (value.is_undefined())
  248. out("\033[34;1m");
  249. if (value.is_string())
  250. out("\"");
  251. else if (value.is_negative_zero())
  252. out("-");
  253. out("{}", value.to_string_without_side_effects());
  254. if (value.is_string())
  255. out("\"");
  256. out("\033[0m");
  257. }
  258. static void print(JS::Value value)
  259. {
  260. HashTable<JS::Object*> seen_objects;
  261. print_value(value, seen_objects);
  262. outln();
  263. }
  264. static bool file_has_shebang(AK::ByteBuffer file_contents)
  265. {
  266. if (file_contents.size() >= 2 && file_contents[0] == '#' && file_contents[1] == '!')
  267. return true;
  268. return false;
  269. }
  270. static StringView strip_shebang(AK::ByteBuffer file_contents)
  271. {
  272. size_t i = 0;
  273. for (i = 2; i < file_contents.size(); ++i) {
  274. if (file_contents[i] == '\n')
  275. break;
  276. }
  277. return StringView((const char*)file_contents.data() + i, file_contents.size() - i);
  278. }
  279. static bool write_to_file(const StringView& path)
  280. {
  281. int fd = open_with_path_length(path.characters_without_null_termination(), path.length(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  282. for (size_t i = 0; i < repl_statements.size(); i++) {
  283. auto line = repl_statements[i];
  284. if (line.length() && i != repl_statements.size() - 1) {
  285. ssize_t nwritten = write(fd, line.characters(), line.length());
  286. if (nwritten < 0) {
  287. close(fd);
  288. return false;
  289. }
  290. }
  291. if (i != repl_statements.size() - 1) {
  292. char ch = '\n';
  293. ssize_t nwritten = write(fd, &ch, 1);
  294. if (nwritten != 1) {
  295. perror("write");
  296. close(fd);
  297. return false;
  298. }
  299. }
  300. }
  301. close(fd);
  302. return true;
  303. }
  304. static bool parse_and_run(JS::Interpreter& interpreter, const StringView& source)
  305. {
  306. auto parser = JS::Parser(JS::Lexer(source));
  307. auto program = parser.parse_program();
  308. if (s_dump_ast)
  309. program->dump(0);
  310. if (parser.has_errors()) {
  311. auto error = parser.errors()[0];
  312. auto hint = error.source_location_hint(source);
  313. if (!hint.is_empty())
  314. outln("{}", hint);
  315. vm->throw_exception<JS::SyntaxError>(interpreter.global_object(), error.to_string());
  316. } else {
  317. interpreter.run(interpreter.global_object(), *program);
  318. }
  319. if (vm->exception()) {
  320. out("Uncaught exception: ");
  321. print(vm->exception()->value());
  322. auto trace = vm->exception()->trace();
  323. if (trace.size() > 1) {
  324. unsigned repetitions = 0;
  325. for (size_t i = 0; i < trace.size(); ++i) {
  326. auto& function_name = trace[i];
  327. if (i + 1 < trace.size() && trace[i + 1] == function_name) {
  328. repetitions++;
  329. continue;
  330. }
  331. if (repetitions > 4) {
  332. // If more than 5 (1 + >4) consecutive function calls with the same name, print
  333. // the name only once and show the number of repetitions instead. This prevents
  334. // printing ridiculously large call stacks of recursive functions.
  335. outln(" -> {}", function_name);
  336. outln(" {} more calls", repetitions);
  337. } else {
  338. for (size_t j = 0; j < repetitions + 1; ++j)
  339. outln(" -> {}", function_name);
  340. }
  341. repetitions = 0;
  342. }
  343. }
  344. vm->clear_exception();
  345. return false;
  346. }
  347. if (s_print_last_result)
  348. print(vm->last_value());
  349. return true;
  350. }
  351. ReplObject::ReplObject()
  352. {
  353. }
  354. void ReplObject::initialize()
  355. {
  356. GlobalObject::initialize();
  357. define_property("global", this, JS::Attribute::Enumerable);
  358. define_native_function("exit", exit_interpreter);
  359. define_native_function("help", repl_help);
  360. define_native_function("load", load_file, 1);
  361. define_native_function("save", save_to_file, 1);
  362. }
  363. ReplObject::~ReplObject()
  364. {
  365. }
  366. JS_DEFINE_NATIVE_FUNCTION(ReplObject::save_to_file)
  367. {
  368. if (!vm.argument_count())
  369. return JS::Value(false);
  370. String save_path = vm.argument(0).to_string_without_side_effects();
  371. StringView path = StringView(save_path.characters());
  372. if (write_to_file(path)) {
  373. return JS::Value(true);
  374. }
  375. return JS::Value(false);
  376. }
  377. JS_DEFINE_NATIVE_FUNCTION(ReplObject::exit_interpreter)
  378. {
  379. if (!vm.argument_count())
  380. exit(0);
  381. auto exit_code = vm.argument(0).to_number(global_object);
  382. if (::vm->exception())
  383. return {};
  384. exit(exit_code.as_double());
  385. }
  386. JS_DEFINE_NATIVE_FUNCTION(ReplObject::repl_help)
  387. {
  388. outln("REPL commands:");
  389. outln(" exit(code): exit the REPL with specified code. Defaults to 0.");
  390. outln(" help(): display this menu");
  391. outln(" load(files): accepts file names as params to load into running session. For example load(\"js/1.js\", \"js/2.js\", \"js/3.js\")");
  392. outln(" save(file): accepts a file name, writes REPL input history to a file. For example: save(\"foo.txt\")");
  393. return JS::js_undefined();
  394. }
  395. JS_DEFINE_NATIVE_FUNCTION(ReplObject::load_file)
  396. {
  397. if (!vm.argument_count())
  398. return JS::Value(false);
  399. for (auto& file : vm.call_frame().arguments) {
  400. String file_name = file.as_string().string();
  401. auto js_file = Core::File::construct(file_name);
  402. if (!js_file->open(Core::IODevice::ReadOnly)) {
  403. warnln("Failed to open {}: {}", file_name, js_file->error_string());
  404. continue;
  405. }
  406. auto file_contents = js_file->read_all();
  407. StringView source;
  408. if (file_has_shebang(file_contents)) {
  409. source = strip_shebang(file_contents);
  410. } else {
  411. source = file_contents;
  412. }
  413. parse_and_run(vm.interpreter(), source);
  414. }
  415. return JS::Value(true);
  416. }
  417. static void repl(JS::Interpreter& interpreter)
  418. {
  419. while (!s_fail_repl) {
  420. String piece = read_next_piece();
  421. if (piece.is_empty())
  422. continue;
  423. repl_statements.append(piece);
  424. parse_and_run(interpreter, piece);
  425. }
  426. }
  427. static Function<void()> interrupt_interpreter;
  428. static void sigint_handler()
  429. {
  430. interrupt_interpreter();
  431. }
  432. class ReplConsoleClient final : public JS::ConsoleClient {
  433. public:
  434. ReplConsoleClient(JS::Console& console)
  435. : ConsoleClient(console)
  436. {
  437. }
  438. virtual JS::Value log() override
  439. {
  440. outln("{}", vm().join_arguments());
  441. return JS::js_undefined();
  442. }
  443. virtual JS::Value info() override
  444. {
  445. outln("(i) {}", vm().join_arguments());
  446. return JS::js_undefined();
  447. }
  448. virtual JS::Value debug() override
  449. {
  450. outln("\033[36;1m{}\033[0m", vm().join_arguments());
  451. return JS::js_undefined();
  452. }
  453. virtual JS::Value warn() override
  454. {
  455. outln("\033[33;1m{}\033[0m", vm().join_arguments());
  456. return JS::js_undefined();
  457. }
  458. virtual JS::Value error() override
  459. {
  460. outln("\033[31;1m{}\033[0m", vm().join_arguments());
  461. return JS::js_undefined();
  462. }
  463. virtual JS::Value clear() override
  464. {
  465. out("\033[3J\033[H\033[2J");
  466. fflush(stdout);
  467. return JS::js_undefined();
  468. }
  469. virtual JS::Value trace() override
  470. {
  471. outln("{}", vm().join_arguments());
  472. auto trace = get_trace();
  473. for (auto& function_name : trace) {
  474. if (function_name.is_empty())
  475. function_name = "<anonymous>";
  476. outln(" -> {}", function_name);
  477. }
  478. return JS::js_undefined();
  479. }
  480. virtual JS::Value count() override
  481. {
  482. auto label = vm().argument_count() ? vm().argument(0).to_string_without_side_effects() : "default";
  483. auto counter_value = m_console.counter_increment(label);
  484. outln("{}: {}", label, counter_value);
  485. return JS::js_undefined();
  486. }
  487. virtual JS::Value count_reset() override
  488. {
  489. auto label = vm().argument_count() ? vm().argument(0).to_string_without_side_effects() : "default";
  490. if (m_console.counter_reset(label))
  491. outln("{}: 0", label);
  492. else
  493. outln("\033[33;1m\"{}\" doesn't have a count\033[0m", label);
  494. return JS::js_undefined();
  495. }
  496. };
  497. int main(int argc, char** argv)
  498. {
  499. bool gc_on_every_allocation = false;
  500. bool disable_syntax_highlight = false;
  501. const char* script_path = nullptr;
  502. Core::ArgsParser args_parser;
  503. args_parser.add_option(s_dump_ast, "Dump the AST", "dump-ast", 'A');
  504. args_parser.add_option(s_print_last_result, "Print last result", "print-last-result", 'l');
  505. args_parser.add_option(gc_on_every_allocation, "GC on every allocation", "gc-on-every-allocation", 'g');
  506. args_parser.add_option(disable_syntax_highlight, "Disable live syntax highlighting", "no-syntax-highlight", 's');
  507. args_parser.add_positional_argument(script_path, "Path to script file", "script", Core::ArgsParser::Required::No);
  508. args_parser.parse(argc, argv);
  509. bool syntax_highlight = !disable_syntax_highlight;
  510. vm = JS::VM::create();
  511. OwnPtr<JS::Interpreter> interpreter;
  512. interrupt_interpreter = [&] {
  513. auto error = JS::Error::create(interpreter->global_object(), "Error", "Received SIGINT");
  514. vm->throw_exception(interpreter->global_object(), error);
  515. };
  516. if (script_path == nullptr) {
  517. s_print_last_result = true;
  518. interpreter = JS::Interpreter::create<ReplObject>(*vm);
  519. ReplConsoleClient console_client(interpreter->global_object().console());
  520. interpreter->global_object().console().set_client(console_client);
  521. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  522. interpreter->vm().set_underscore_is_last_value(true);
  523. s_editor = Line::Editor::construct();
  524. s_editor->load_history(s_history_path);
  525. signal(SIGINT, [](int) {
  526. if (!s_editor->is_editing())
  527. sigint_handler();
  528. s_editor->save_history(s_history_path);
  529. });
  530. s_editor->on_display_refresh = [syntax_highlight](Line::Editor& editor) {
  531. auto stylize = [&](Line::Span span, Line::Style styles) {
  532. if (syntax_highlight)
  533. editor.stylize(span, styles);
  534. };
  535. editor.strip_styles();
  536. size_t open_indents = s_repl_line_level;
  537. auto line = editor.line();
  538. JS::Lexer lexer(line);
  539. bool indenters_starting_line = true;
  540. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  541. auto length = token.value().length();
  542. auto start = token.line_column() - 1;
  543. auto end = start + length;
  544. if (indenters_starting_line) {
  545. if (token.type() != JS::TokenType::ParenClose && token.type() != JS::TokenType::BracketClose && token.type() != JS::TokenType::CurlyClose) {
  546. indenters_starting_line = false;
  547. } else {
  548. --open_indents;
  549. }
  550. }
  551. switch (token.category()) {
  552. case JS::TokenCategory::Invalid:
  553. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Red), Line::Style::Underline });
  554. break;
  555. case JS::TokenCategory::Number:
  556. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Magenta) });
  557. break;
  558. case JS::TokenCategory::String:
  559. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Green), Line::Style::Bold });
  560. break;
  561. case JS::TokenCategory::Punctuation:
  562. break;
  563. case JS::TokenCategory::Operator:
  564. break;
  565. case JS::TokenCategory::Keyword:
  566. switch (token.type()) {
  567. case JS::TokenType::BoolLiteral:
  568. case JS::TokenType::NullLiteral:
  569. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow), Line::Style::Bold });
  570. break;
  571. default:
  572. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Blue), Line::Style::Bold });
  573. break;
  574. }
  575. break;
  576. case JS::TokenCategory::ControlKeyword:
  577. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan), Line::Style::Italic });
  578. break;
  579. case JS::TokenCategory::Identifier:
  580. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::White), Line::Style::Bold });
  581. default:
  582. break;
  583. }
  584. }
  585. editor.set_prompt(prompt_for_level(open_indents));
  586. };
  587. auto complete = [&interpreter](const Line::Editor& editor) -> Vector<Line::CompletionSuggestion> {
  588. auto line = editor.line(editor.cursor());
  589. JS::Lexer lexer { line };
  590. enum {
  591. Initial,
  592. CompleteVariable,
  593. CompleteNullProperty,
  594. CompleteProperty,
  595. } mode { Initial };
  596. StringView variable_name;
  597. StringView property_name;
  598. // we're only going to complete either
  599. // - <N>
  600. // where N is part of the name of a variable
  601. // - <N>.<P>
  602. // where N is the complete name of a variable and
  603. // P is part of the name of one of its properties
  604. auto js_token = lexer.next();
  605. for (; js_token.type() != JS::TokenType::Eof; js_token = lexer.next()) {
  606. switch (mode) {
  607. case CompleteVariable:
  608. switch (js_token.type()) {
  609. case JS::TokenType::Period:
  610. // ...<name> <dot>
  611. mode = CompleteNullProperty;
  612. break;
  613. default:
  614. // not a dot, reset back to initial
  615. mode = Initial;
  616. break;
  617. }
  618. break;
  619. case CompleteNullProperty:
  620. if (js_token.is_identifier_name()) {
  621. // ...<name> <dot> <name>
  622. mode = CompleteProperty;
  623. property_name = js_token.value();
  624. } else {
  625. mode = Initial;
  626. }
  627. break;
  628. case CompleteProperty:
  629. // something came after the property access, reset to initial
  630. case Initial:
  631. if (js_token.is_identifier_name()) {
  632. // ...<name>...
  633. mode = CompleteVariable;
  634. variable_name = js_token.value();
  635. } else {
  636. mode = Initial;
  637. }
  638. break;
  639. }
  640. }
  641. bool last_token_has_trivia = js_token.trivia().length() > 0;
  642. if (mode == CompleteNullProperty) {
  643. mode = CompleteProperty;
  644. property_name = "";
  645. last_token_has_trivia = false; // <name> <dot> [tab] is sensible to complete.
  646. }
  647. if (mode == Initial || last_token_has_trivia)
  648. return {}; // we do not know how to complete this
  649. Vector<Line::CompletionSuggestion> results;
  650. Function<void(const JS::Shape&, const StringView&)> list_all_properties = [&results, &list_all_properties](const JS::Shape& shape, auto& property_pattern) {
  651. for (const auto& descriptor : shape.property_table()) {
  652. if (!descriptor.key.is_string())
  653. continue;
  654. auto key = descriptor.key.as_string();
  655. if (key.view().starts_with(property_pattern)) {
  656. Line::CompletionSuggestion completion { key, Line::CompletionSuggestion::ForSearch };
  657. if (!results.contains_slow(completion)) { // hide duplicates
  658. results.append(key);
  659. }
  660. }
  661. }
  662. if (const auto* prototype = shape.prototype()) {
  663. list_all_properties(prototype->shape(), property_pattern);
  664. }
  665. };
  666. switch (mode) {
  667. case CompleteProperty: {
  668. auto maybe_variable = vm->get_variable(variable_name, interpreter->global_object());
  669. if (maybe_variable.is_empty()) {
  670. maybe_variable = interpreter->global_object().get(FlyString(variable_name));
  671. if (maybe_variable.is_empty())
  672. break;
  673. }
  674. auto variable = maybe_variable;
  675. if (!variable.is_object())
  676. break;
  677. const auto* object = variable.to_object(interpreter->global_object());
  678. const auto& shape = object->shape();
  679. list_all_properties(shape, property_name);
  680. if (results.size())
  681. editor.suggest(property_name.length());
  682. break;
  683. }
  684. case CompleteVariable: {
  685. const auto& variable = interpreter->global_object();
  686. list_all_properties(variable.shape(), variable_name);
  687. if (results.size())
  688. editor.suggest(variable_name.length());
  689. break;
  690. }
  691. default:
  692. ASSERT_NOT_REACHED();
  693. }
  694. return results;
  695. };
  696. s_editor->on_tab_complete = move(complete);
  697. repl(*interpreter);
  698. s_editor->save_history(s_history_path);
  699. } else {
  700. interpreter = JS::Interpreter::create<JS::GlobalObject>(*vm);
  701. ReplConsoleClient console_client(interpreter->global_object().console());
  702. interpreter->global_object().console().set_client(console_client);
  703. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  704. signal(SIGINT, [](int) {
  705. sigint_handler();
  706. });
  707. auto file = Core::File::construct(script_path);
  708. if (!file->open(Core::IODevice::ReadOnly)) {
  709. warnln("Failed to open {}: {}", script_path, file->error_string());
  710. return 1;
  711. }
  712. auto file_contents = file->read_all();
  713. StringView source;
  714. if (file_has_shebang(file_contents)) {
  715. source = strip_shebang(file_contents);
  716. } else {
  717. source = file_contents;
  718. }
  719. if (!parse_and_run(*interpreter, source))
  720. return 1;
  721. }
  722. return 0;
  723. }