js.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2020-2022, Ali Mohammad Pur <mpfard@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <LibCore/ArgsParser.h>
  9. #include <LibCore/ConfigFile.h>
  10. #include <LibCore/StandardPaths.h>
  11. #include <LibCore/Stream.h>
  12. #include <LibCore/System.h>
  13. #include <LibJS/Bytecode/BasicBlock.h>
  14. #include <LibJS/Bytecode/Generator.h>
  15. #include <LibJS/Bytecode/Interpreter.h>
  16. #include <LibJS/Console.h>
  17. #include <LibJS/Interpreter.h>
  18. #include <LibJS/Parser.h>
  19. #include <LibJS/Print.h>
  20. #include <LibJS/Runtime/ConsoleObject.h>
  21. #include <LibJS/Runtime/JSONObject.h>
  22. #include <LibJS/Runtime/StringPrototype.h>
  23. #include <LibJS/SourceTextModule.h>
  24. #include <LibLine/Editor.h>
  25. #include <LibMain/Main.h>
  26. #include <LibTextCodec/Decoder.h>
  27. #include <fcntl.h>
  28. #include <signal.h>
  29. #include <stdio.h>
  30. #include <unistd.h>
  31. RefPtr<JS::VM> g_vm;
  32. Vector<String> g_repl_statements;
  33. JS::Handle<JS::Value> g_last_value = JS::make_handle(JS::js_undefined());
  34. class ReplObject final : public JS::GlobalObject {
  35. JS_OBJECT(ReplObject, JS::GlobalObject);
  36. public:
  37. ReplObject(JS::Realm& realm)
  38. : GlobalObject(realm)
  39. {
  40. }
  41. virtual void initialize(JS::Realm&) override;
  42. virtual ~ReplObject() override = default;
  43. private:
  44. JS_DECLARE_NATIVE_FUNCTION(exit_interpreter);
  45. JS_DECLARE_NATIVE_FUNCTION(repl_help);
  46. JS_DECLARE_NATIVE_FUNCTION(save_to_file);
  47. JS_DECLARE_NATIVE_FUNCTION(load_ini);
  48. JS_DECLARE_NATIVE_FUNCTION(load_json);
  49. JS_DECLARE_NATIVE_FUNCTION(last_value_getter);
  50. JS_DECLARE_NATIVE_FUNCTION(print);
  51. };
  52. class ScriptObject final : public JS::GlobalObject {
  53. JS_OBJECT(ScriptObject, JS::GlobalObject);
  54. public:
  55. ScriptObject(JS::Realm& realm)
  56. : JS::GlobalObject(realm)
  57. {
  58. }
  59. virtual void initialize(JS::Realm&) override;
  60. virtual ~ScriptObject() override = default;
  61. private:
  62. JS_DECLARE_NATIVE_FUNCTION(load_ini);
  63. JS_DECLARE_NATIVE_FUNCTION(load_json);
  64. JS_DECLARE_NATIVE_FUNCTION(print);
  65. };
  66. static bool s_dump_ast = false;
  67. static bool s_run_bytecode = false;
  68. static bool s_opt_bytecode = false;
  69. static bool s_as_module = false;
  70. static bool s_print_last_result = false;
  71. static bool s_strip_ansi = false;
  72. static bool s_disable_source_location_hints = false;
  73. static RefPtr<Line::Editor> s_editor;
  74. static String s_history_path = String::formatted("{}/.js-history", Core::StandardPaths::home_directory());
  75. static int s_repl_line_level = 0;
  76. static bool s_fail_repl = false;
  77. static ErrorOr<void> print(JS::Value value, Core::Stream::Stream& stream)
  78. {
  79. JS::PrintContext print_context { .vm = *g_vm, .stream = stream, .strip_ansi = s_strip_ansi };
  80. return JS::print(value, print_context);
  81. }
  82. enum class PrintTarget {
  83. StandardError,
  84. StandardOutput,
  85. };
  86. static ErrorOr<void> print(JS::Value value, PrintTarget target = PrintTarget::StandardOutput)
  87. {
  88. auto stream = TRY(target == PrintTarget::StandardError ? Core::Stream::File::standard_error() : Core::Stream::File::standard_output());
  89. return print(value, *stream);
  90. }
  91. static String prompt_for_level(int level)
  92. {
  93. static StringBuilder prompt_builder;
  94. prompt_builder.clear();
  95. prompt_builder.append("> "sv);
  96. for (auto i = 0; i < level; ++i)
  97. prompt_builder.append(" "sv);
  98. return prompt_builder.build();
  99. }
  100. static String read_next_piece()
  101. {
  102. StringBuilder piece;
  103. auto line_level_delta_for_next_line { 0 };
  104. do {
  105. auto line_result = s_editor->get_line(prompt_for_level(s_repl_line_level));
  106. line_level_delta_for_next_line = 0;
  107. if (line_result.is_error()) {
  108. s_fail_repl = true;
  109. return "";
  110. }
  111. auto& line = line_result.value();
  112. s_editor->add_to_history(line);
  113. piece.append(line);
  114. piece.append('\n');
  115. auto lexer = JS::Lexer(line);
  116. enum {
  117. NotInLabelOrObjectKey,
  118. InLabelOrObjectKeyIdentifier,
  119. InLabelOrObjectKey
  120. } label_state { NotInLabelOrObjectKey };
  121. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  122. switch (token.type()) {
  123. case JS::TokenType::BracketOpen:
  124. case JS::TokenType::CurlyOpen:
  125. case JS::TokenType::ParenOpen:
  126. label_state = NotInLabelOrObjectKey;
  127. s_repl_line_level++;
  128. break;
  129. case JS::TokenType::BracketClose:
  130. case JS::TokenType::CurlyClose:
  131. case JS::TokenType::ParenClose:
  132. label_state = NotInLabelOrObjectKey;
  133. s_repl_line_level--;
  134. break;
  135. case JS::TokenType::Identifier:
  136. case JS::TokenType::StringLiteral:
  137. if (label_state == NotInLabelOrObjectKey)
  138. label_state = InLabelOrObjectKeyIdentifier;
  139. else
  140. label_state = NotInLabelOrObjectKey;
  141. break;
  142. case JS::TokenType::Colon:
  143. if (label_state == InLabelOrObjectKeyIdentifier)
  144. label_state = InLabelOrObjectKey;
  145. else
  146. label_state = NotInLabelOrObjectKey;
  147. break;
  148. default:
  149. break;
  150. }
  151. }
  152. if (label_state == InLabelOrObjectKey) {
  153. // If there's a label or object literal key at the end of this line,
  154. // prompt for more lines but do not change the line level.
  155. line_level_delta_for_next_line += 1;
  156. }
  157. } while (s_repl_line_level + line_level_delta_for_next_line > 0);
  158. return piece.to_string();
  159. }
  160. static bool write_to_file(String const& path)
  161. {
  162. int fd = open(path.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  163. for (size_t i = 0; i < g_repl_statements.size(); i++) {
  164. auto line = g_repl_statements[i];
  165. if (line.length() && i != g_repl_statements.size() - 1) {
  166. ssize_t nwritten = write(fd, line.characters(), line.length());
  167. if (nwritten < 0) {
  168. close(fd);
  169. return false;
  170. }
  171. }
  172. if (i != g_repl_statements.size() - 1) {
  173. char ch = '\n';
  174. ssize_t nwritten = write(fd, &ch, 1);
  175. if (nwritten != 1) {
  176. perror("write");
  177. close(fd);
  178. return false;
  179. }
  180. }
  181. }
  182. close(fd);
  183. return true;
  184. }
  185. static ErrorOr<bool> parse_and_run(JS::Interpreter& interpreter, StringView source, StringView source_name)
  186. {
  187. enum class ReturnEarly {
  188. No,
  189. Yes,
  190. };
  191. JS::ThrowCompletionOr<JS::Value> result { JS::js_undefined() };
  192. auto run_script_or_module = [&](auto& script_or_module) {
  193. if (s_dump_ast)
  194. script_or_module->parse_node().dump(0);
  195. if (JS::Bytecode::g_dump_bytecode || s_run_bytecode) {
  196. auto executable_result = JS::Bytecode::Generator::generate(script_or_module->parse_node());
  197. if (executable_result.is_error()) {
  198. result = g_vm->throw_completion<JS::InternalError>(executable_result.error().to_string());
  199. return ReturnEarly::No;
  200. }
  201. auto executable = executable_result.release_value();
  202. executable->name = source_name;
  203. if (s_opt_bytecode) {
  204. auto& passes = JS::Bytecode::Interpreter::optimization_pipeline(JS::Bytecode::Interpreter::OptimizationLevel::Optimize);
  205. passes.perform(*executable);
  206. dbgln("Optimisation passes took {}us", passes.elapsed());
  207. }
  208. if (JS::Bytecode::g_dump_bytecode)
  209. executable->dump();
  210. if (s_run_bytecode) {
  211. JS::Bytecode::Interpreter bytecode_interpreter(interpreter.realm());
  212. auto result_or_error = bytecode_interpreter.run_and_return_frame(*executable, nullptr);
  213. if (result_or_error.value.is_error())
  214. result = result_or_error.value.release_error();
  215. else
  216. result = result_or_error.frame->registers[0];
  217. } else {
  218. return ReturnEarly::Yes;
  219. }
  220. } else {
  221. result = interpreter.run(*script_or_module);
  222. }
  223. return ReturnEarly::No;
  224. };
  225. if (!s_as_module) {
  226. auto script_or_error = JS::Script::parse(source, interpreter.realm(), source_name);
  227. if (script_or_error.is_error()) {
  228. auto error = script_or_error.error()[0];
  229. auto hint = error.source_location_hint(source);
  230. if (!hint.is_empty())
  231. outln("{}", hint);
  232. outln("{}", error.to_string());
  233. result = interpreter.vm().throw_completion<JS::SyntaxError>(error.to_string());
  234. } else {
  235. auto return_early = run_script_or_module(script_or_error.value());
  236. if (return_early == ReturnEarly::Yes)
  237. return true;
  238. }
  239. } else {
  240. auto module_or_error = JS::SourceTextModule::parse(source, interpreter.realm(), source_name);
  241. if (module_or_error.is_error()) {
  242. auto error = module_or_error.error()[0];
  243. auto hint = error.source_location_hint(source);
  244. if (!hint.is_empty())
  245. outln("{}", hint);
  246. outln(error.to_string());
  247. result = interpreter.vm().throw_completion<JS::SyntaxError>(error.to_string());
  248. } else {
  249. auto return_early = run_script_or_module(module_or_error.value());
  250. if (return_early == ReturnEarly::Yes)
  251. return true;
  252. }
  253. }
  254. auto handle_exception = [&](JS::Value thrown_value) -> ErrorOr<void> {
  255. warnln("Uncaught exception: ");
  256. TRY(print(thrown_value, PrintTarget::StandardError));
  257. warnln();
  258. if (!thrown_value.is_object() || !is<JS::Error>(thrown_value.as_object()))
  259. return {};
  260. auto& traceback = static_cast<JS::Error const&>(thrown_value.as_object()).traceback();
  261. if (traceback.size() > 1) {
  262. unsigned repetitions = 0;
  263. for (size_t i = 0; i < traceback.size(); ++i) {
  264. auto& traceback_frame = traceback[i];
  265. if (i + 1 < traceback.size()) {
  266. auto& next_traceback_frame = traceback[i + 1];
  267. if (next_traceback_frame.function_name == traceback_frame.function_name) {
  268. repetitions++;
  269. continue;
  270. }
  271. }
  272. if (repetitions > 4) {
  273. // If more than 5 (1 + >4) consecutive function calls with the same name, print
  274. // the name only once and show the number of repetitions instead. This prevents
  275. // printing ridiculously large call stacks of recursive functions.
  276. warnln(" -> {}", traceback_frame.function_name);
  277. warnln(" {} more calls", repetitions);
  278. } else {
  279. for (size_t j = 0; j < repetitions + 1; ++j)
  280. warnln(" -> {}", traceback_frame.function_name);
  281. }
  282. repetitions = 0;
  283. }
  284. }
  285. return {};
  286. };
  287. if (!result.is_error())
  288. g_last_value = JS::make_handle(result.value());
  289. if (result.is_error()) {
  290. VERIFY(result.throw_completion().value().has_value());
  291. TRY(handle_exception(*result.release_error().value()));
  292. return false;
  293. }
  294. if (s_print_last_result) {
  295. TRY(print(result.value()));
  296. warnln();
  297. }
  298. return true;
  299. }
  300. static JS::ThrowCompletionOr<JS::Value> load_ini_impl(JS::VM& vm)
  301. {
  302. auto& realm = *vm.current_realm();
  303. auto filename = TRY(vm.argument(0).to_string(vm));
  304. auto file_or_error = Core::Stream::File::open(filename, Core::Stream::OpenMode::Read);
  305. if (file_or_error.is_error())
  306. return vm.throw_completion<JS::Error>(String::formatted("Failed to open '{}': {}", filename, file_or_error.error()));
  307. auto config_file = MUST(Core::ConfigFile::open(filename, file_or_error.release_value()));
  308. auto* object = JS::Object::create(realm, realm.intrinsics().object_prototype());
  309. for (auto const& group : config_file->groups()) {
  310. auto* group_object = JS::Object::create(realm, realm.intrinsics().object_prototype());
  311. for (auto const& key : config_file->keys(group)) {
  312. auto entry = config_file->read_entry(group, key);
  313. group_object->define_direct_property(key, js_string(vm, move(entry)), JS::Attribute::Enumerable | JS::Attribute::Configurable | JS::Attribute::Writable);
  314. }
  315. object->define_direct_property(group, group_object, JS::Attribute::Enumerable | JS::Attribute::Configurable | JS::Attribute::Writable);
  316. }
  317. return object;
  318. }
  319. static JS::ThrowCompletionOr<JS::Value> load_json_impl(JS::VM& vm)
  320. {
  321. auto filename = TRY(vm.argument(0).to_string(vm));
  322. auto file_or_error = Core::Stream::File::open(filename, Core::Stream::OpenMode::Read);
  323. if (file_or_error.is_error())
  324. return vm.throw_completion<JS::Error>(String::formatted("Failed to open '{}': {}", filename, file_or_error.error()));
  325. auto file_contents_or_error = file_or_error.value()->read_all();
  326. if (file_contents_or_error.is_error())
  327. return vm.throw_completion<JS::Error>(String::formatted("Failed to read '{}': {}", filename, file_contents_or_error.error()));
  328. auto json = JsonValue::from_string(file_contents_or_error.value());
  329. if (json.is_error())
  330. return vm.throw_completion<JS::SyntaxError>(JS::ErrorType::JsonMalformed);
  331. return JS::JSONObject::parse_json_value(vm, json.value());
  332. }
  333. void ReplObject::initialize(JS::Realm& realm)
  334. {
  335. Base::initialize(realm);
  336. define_direct_property("global", this, JS::Attribute::Enumerable);
  337. u8 attr = JS::Attribute::Configurable | JS::Attribute::Writable | JS::Attribute::Enumerable;
  338. define_native_function(realm, "exit", exit_interpreter, 0, attr);
  339. define_native_function(realm, "help", repl_help, 0, attr);
  340. define_native_function(realm, "save", save_to_file, 1, attr);
  341. define_native_function(realm, "loadINI", load_ini, 1, attr);
  342. define_native_function(realm, "loadJSON", load_json, 1, attr);
  343. define_native_function(realm, "print", print, 1, attr);
  344. define_native_accessor(
  345. realm,
  346. "_",
  347. [](JS::VM&) {
  348. return g_last_value.value();
  349. },
  350. [](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
  351. auto& global_object = vm.get_global_object();
  352. VERIFY(is<ReplObject>(global_object));
  353. outln("Disable writing last value to '_'");
  354. // We must delete first otherwise this setter gets called recursively.
  355. TRY(global_object.internal_delete(JS::PropertyKey { "_" }));
  356. auto value = vm.argument(0);
  357. TRY(global_object.internal_set(JS::PropertyKey { "_" }, value, &global_object));
  358. return value;
  359. },
  360. attr);
  361. }
  362. JS_DEFINE_NATIVE_FUNCTION(ReplObject::save_to_file)
  363. {
  364. if (!vm.argument_count())
  365. return JS::Value(false);
  366. String save_path = vm.argument(0).to_string_without_side_effects();
  367. if (write_to_file(save_path)) {
  368. return JS::Value(true);
  369. }
  370. return JS::Value(false);
  371. }
  372. JS_DEFINE_NATIVE_FUNCTION(ReplObject::exit_interpreter)
  373. {
  374. if (!vm.argument_count())
  375. exit(0);
  376. exit(TRY(vm.argument(0).to_number(vm)).as_double());
  377. }
  378. JS_DEFINE_NATIVE_FUNCTION(ReplObject::repl_help)
  379. {
  380. warnln("REPL commands:");
  381. warnln(" exit(code): exit the REPL with specified code. Defaults to 0.");
  382. warnln(" help(): display this menu");
  383. warnln(" loadINI(file): load the given file as INI.");
  384. warnln(" loadJSON(file): load the given file as JSON.");
  385. warnln(" print(value): pretty-print the given JS value.");
  386. warnln(" save(file): write REPL input history to the given file. For example: save(\"foo.txt\")");
  387. return JS::js_undefined();
  388. }
  389. JS_DEFINE_NATIVE_FUNCTION(ReplObject::load_ini)
  390. {
  391. return load_ini_impl(vm);
  392. }
  393. JS_DEFINE_NATIVE_FUNCTION(ReplObject::load_json)
  394. {
  395. return load_json_impl(vm);
  396. }
  397. JS_DEFINE_NATIVE_FUNCTION(ReplObject::print)
  398. {
  399. auto result = ::print(vm.argument(0));
  400. if (result.is_error())
  401. return g_vm->throw_completion<JS::InternalError>(String::formatted("Failed to print value: {}", result.error()));
  402. outln();
  403. return JS::js_undefined();
  404. }
  405. void ScriptObject::initialize(JS::Realm& realm)
  406. {
  407. Base::initialize(realm);
  408. define_direct_property("global", this, JS::Attribute::Enumerable);
  409. u8 attr = JS::Attribute::Configurable | JS::Attribute::Writable | JS::Attribute::Enumerable;
  410. define_native_function(realm, "loadINI", load_ini, 1, attr);
  411. define_native_function(realm, "loadJSON", load_json, 1, attr);
  412. define_native_function(realm, "print", print, 1, attr);
  413. }
  414. JS_DEFINE_NATIVE_FUNCTION(ScriptObject::load_ini)
  415. {
  416. return load_ini_impl(vm);
  417. }
  418. JS_DEFINE_NATIVE_FUNCTION(ScriptObject::load_json)
  419. {
  420. return load_json_impl(vm);
  421. }
  422. JS_DEFINE_NATIVE_FUNCTION(ScriptObject::print)
  423. {
  424. auto result = ::print(vm.argument(0));
  425. if (result.is_error())
  426. return g_vm->throw_completion<JS::InternalError>(String::formatted("Failed to print value: {}", result.error()));
  427. outln();
  428. return JS::js_undefined();
  429. }
  430. static ErrorOr<void> repl(JS::Interpreter& interpreter)
  431. {
  432. while (!s_fail_repl) {
  433. String piece = read_next_piece();
  434. if (Utf8View { piece }.trim(JS::whitespace_characters).is_empty())
  435. continue;
  436. g_repl_statements.append(piece);
  437. TRY(parse_and_run(interpreter, piece, "REPL"sv));
  438. }
  439. return {};
  440. }
  441. static Function<void()> interrupt_interpreter;
  442. static void sigint_handler()
  443. {
  444. interrupt_interpreter();
  445. }
  446. class ReplConsoleClient final : public JS::ConsoleClient {
  447. public:
  448. ReplConsoleClient(JS::Console& console)
  449. : ConsoleClient(console)
  450. {
  451. }
  452. virtual void clear() override
  453. {
  454. out("\033[3J\033[H\033[2J");
  455. m_group_stack_depth = 0;
  456. fflush(stdout);
  457. }
  458. virtual void end_group() override
  459. {
  460. if (m_group_stack_depth > 0)
  461. m_group_stack_depth--;
  462. }
  463. // 2.3. Printer(logLevel, args[, options]), https://console.spec.whatwg.org/#printer
  464. virtual JS::ThrowCompletionOr<JS::Value> printer(JS::Console::LogLevel log_level, PrinterArguments arguments) override
  465. {
  466. String indent = String::repeated(" "sv, m_group_stack_depth);
  467. if (log_level == JS::Console::LogLevel::Trace) {
  468. auto trace = arguments.get<JS::Console::Trace>();
  469. StringBuilder builder;
  470. if (!trace.label.is_empty())
  471. builder.appendff("{}\033[36;1m{}\033[0m\n", indent, trace.label);
  472. for (auto& function_name : trace.stack)
  473. builder.appendff("{}-> {}\n", indent, function_name);
  474. outln("{}", builder.string_view());
  475. return JS::js_undefined();
  476. }
  477. if (log_level == JS::Console::LogLevel::Group || log_level == JS::Console::LogLevel::GroupCollapsed) {
  478. auto group = arguments.get<JS::Console::Group>();
  479. outln("{}\033[36;1m{}\033[0m", indent, group.label);
  480. m_group_stack_depth++;
  481. return JS::js_undefined();
  482. }
  483. auto output = String::join(' ', arguments.get<JS::MarkedVector<JS::Value>>());
  484. #ifdef AK_OS_SERENITY
  485. m_console.output_debug_message(log_level, output);
  486. #endif
  487. switch (log_level) {
  488. case JS::Console::LogLevel::Debug:
  489. outln("{}\033[36;1m{}\033[0m", indent, output);
  490. break;
  491. case JS::Console::LogLevel::Error:
  492. case JS::Console::LogLevel::Assert:
  493. outln("{}\033[31;1m{}\033[0m", indent, output);
  494. break;
  495. case JS::Console::LogLevel::Info:
  496. outln("{}(i) {}", indent, output);
  497. break;
  498. case JS::Console::LogLevel::Log:
  499. outln("{}{}", indent, output);
  500. break;
  501. case JS::Console::LogLevel::Warn:
  502. case JS::Console::LogLevel::CountReset:
  503. outln("{}\033[33;1m{}\033[0m", indent, output);
  504. break;
  505. default:
  506. outln("{}{}", indent, output);
  507. break;
  508. }
  509. return JS::js_undefined();
  510. }
  511. private:
  512. int m_group_stack_depth { 0 };
  513. };
  514. ErrorOr<int> serenity_main(Main::Arguments arguments)
  515. {
  516. TRY(Core::System::pledge("stdio rpath wpath cpath tty sigaction"));
  517. bool gc_on_every_allocation = false;
  518. bool disable_syntax_highlight = false;
  519. StringView evaluate_script;
  520. Vector<StringView> script_paths;
  521. Core::ArgsParser args_parser;
  522. args_parser.set_general_help("This is a JavaScript interpreter.");
  523. args_parser.add_option(s_dump_ast, "Dump the AST", "dump-ast", 'A');
  524. args_parser.add_option(JS::Bytecode::g_dump_bytecode, "Dump the bytecode", "dump-bytecode", 'd');
  525. args_parser.add_option(s_run_bytecode, "Run the bytecode", "run-bytecode", 'b');
  526. args_parser.add_option(s_opt_bytecode, "Optimize the bytecode", "optimize-bytecode", 'p');
  527. args_parser.add_option(s_as_module, "Treat as module", "as-module", 'm');
  528. args_parser.add_option(s_print_last_result, "Print last result", "print-last-result", 'l');
  529. args_parser.add_option(s_strip_ansi, "Disable ANSI colors", "disable-ansi-colors", 'i');
  530. args_parser.add_option(s_disable_source_location_hints, "Disable source location hints", "disable-source-location-hints", 'h');
  531. args_parser.add_option(gc_on_every_allocation, "GC on every allocation", "gc-on-every-allocation", 'g');
  532. args_parser.add_option(disable_syntax_highlight, "Disable live syntax highlighting", "no-syntax-highlight", 's');
  533. args_parser.add_option(evaluate_script, "Evaluate argument as a script", "evaluate", 'c', "script");
  534. args_parser.add_positional_argument(script_paths, "Path to script files", "scripts", Core::ArgsParser::Required::No);
  535. args_parser.parse(arguments);
  536. bool syntax_highlight = !disable_syntax_highlight;
  537. g_vm = JS::VM::create();
  538. g_vm->enable_default_host_import_module_dynamically_hook();
  539. // NOTE: These will print out both warnings when using something like Promise.reject().catch(...) -
  540. // which is, as far as I can tell, correct - a promise is created, rejected without handler, and a
  541. // handler then attached to it. The Node.js REPL doesn't warn in this case, so it's something we
  542. // might want to revisit at a later point and disable warnings for promises created this way.
  543. g_vm->on_promise_unhandled_rejection = [](auto& promise) {
  544. warn("WARNING: A promise was rejected without any handlers");
  545. warn(" (result: ");
  546. (void)print(promise.result(), PrintTarget::StandardError);
  547. warnln(")");
  548. };
  549. g_vm->on_promise_rejection_handled = [](auto& promise) {
  550. warn("WARNING: A handler was added to an already rejected promise");
  551. warn(" (result: ");
  552. (void)print(promise.result(), PrintTarget::StandardError);
  553. warnln(")");
  554. };
  555. OwnPtr<JS::Interpreter> interpreter;
  556. // FIXME: Figure out some way to interrupt the interpreter now that vm.exception() is gone.
  557. if (evaluate_script.is_empty() && script_paths.is_empty()) {
  558. s_print_last_result = true;
  559. interpreter = JS::Interpreter::create<ReplObject>(*g_vm);
  560. auto& console_object = *interpreter->realm().intrinsics().console_object();
  561. ReplConsoleClient console_client(console_object.console());
  562. console_object.console().set_client(console_client);
  563. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  564. auto& global_environment = interpreter->realm().global_environment();
  565. s_editor = Line::Editor::construct();
  566. s_editor->load_history(s_history_path);
  567. signal(SIGINT, [](int) {
  568. if (!s_editor->is_editing())
  569. sigint_handler();
  570. s_editor->save_history(s_history_path);
  571. });
  572. s_editor->on_display_refresh = [syntax_highlight](Line::Editor& editor) {
  573. auto stylize = [&](Line::Span span, Line::Style styles) {
  574. if (syntax_highlight)
  575. editor.stylize(span, styles);
  576. };
  577. editor.strip_styles();
  578. size_t open_indents = s_repl_line_level;
  579. auto line = editor.line();
  580. JS::Lexer lexer(line);
  581. bool indenters_starting_line = true;
  582. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  583. auto length = Utf8View { token.value() }.length();
  584. auto start = token.offset();
  585. auto end = start + length;
  586. if (indenters_starting_line) {
  587. if (token.type() != JS::TokenType::ParenClose && token.type() != JS::TokenType::BracketClose && token.type() != JS::TokenType::CurlyClose) {
  588. indenters_starting_line = false;
  589. } else {
  590. --open_indents;
  591. }
  592. }
  593. switch (token.category()) {
  594. case JS::TokenCategory::Invalid:
  595. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Red), Line::Style::Underline });
  596. break;
  597. case JS::TokenCategory::Number:
  598. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Magenta) });
  599. break;
  600. case JS::TokenCategory::String:
  601. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Green), Line::Style::Bold });
  602. break;
  603. case JS::TokenCategory::Punctuation:
  604. break;
  605. case JS::TokenCategory::Operator:
  606. break;
  607. case JS::TokenCategory::Keyword:
  608. switch (token.type()) {
  609. case JS::TokenType::BoolLiteral:
  610. case JS::TokenType::NullLiteral:
  611. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow), Line::Style::Bold });
  612. break;
  613. default:
  614. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Blue), Line::Style::Bold });
  615. break;
  616. }
  617. break;
  618. case JS::TokenCategory::ControlKeyword:
  619. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan), Line::Style::Italic });
  620. break;
  621. case JS::TokenCategory::Identifier:
  622. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::White), Line::Style::Bold });
  623. break;
  624. default:
  625. break;
  626. }
  627. }
  628. editor.set_prompt(prompt_for_level(open_indents));
  629. };
  630. auto complete = [&interpreter, &global_environment](Line::Editor const& editor) -> Vector<Line::CompletionSuggestion> {
  631. auto line = editor.line(editor.cursor());
  632. JS::Lexer lexer { line };
  633. enum {
  634. Initial,
  635. CompleteVariable,
  636. CompleteNullProperty,
  637. CompleteProperty,
  638. } mode { Initial };
  639. StringView variable_name;
  640. StringView property_name;
  641. // we're only going to complete either
  642. // - <N>
  643. // where N is part of the name of a variable
  644. // - <N>.<P>
  645. // where N is the complete name of a variable and
  646. // P is part of the name of one of its properties
  647. auto js_token = lexer.next();
  648. for (; js_token.type() != JS::TokenType::Eof; js_token = lexer.next()) {
  649. switch (mode) {
  650. case CompleteVariable:
  651. switch (js_token.type()) {
  652. case JS::TokenType::Period:
  653. // ...<name> <dot>
  654. mode = CompleteNullProperty;
  655. break;
  656. default:
  657. // not a dot, reset back to initial
  658. mode = Initial;
  659. break;
  660. }
  661. break;
  662. case CompleteNullProperty:
  663. if (js_token.is_identifier_name()) {
  664. // ...<name> <dot> <name>
  665. mode = CompleteProperty;
  666. property_name = js_token.value();
  667. } else {
  668. mode = Initial;
  669. }
  670. break;
  671. case CompleteProperty:
  672. // something came after the property access, reset to initial
  673. case Initial:
  674. if (js_token.type() == JS::TokenType::Identifier) {
  675. // ...<name>...
  676. mode = CompleteVariable;
  677. variable_name = js_token.value();
  678. } else {
  679. mode = Initial;
  680. }
  681. break;
  682. }
  683. }
  684. bool last_token_has_trivia = js_token.trivia().length() > 0;
  685. if (mode == CompleteNullProperty) {
  686. mode = CompleteProperty;
  687. property_name = ""sv;
  688. last_token_has_trivia = false; // <name> <dot> [tab] is sensible to complete.
  689. }
  690. if (mode == Initial || last_token_has_trivia)
  691. return {}; // we do not know how to complete this
  692. Vector<Line::CompletionSuggestion> results;
  693. Function<void(JS::Shape const&, StringView)> list_all_properties = [&results, &list_all_properties](JS::Shape const& shape, auto property_pattern) {
  694. for (auto const& descriptor : shape.property_table()) {
  695. if (!descriptor.key.is_string())
  696. continue;
  697. auto key = descriptor.key.as_string();
  698. if (key.view().starts_with(property_pattern)) {
  699. Line::CompletionSuggestion completion { key, Line::CompletionSuggestion::ForSearch };
  700. if (!results.contains_slow(completion)) { // hide duplicates
  701. results.append(String(key));
  702. results.last().invariant_offset = property_pattern.length();
  703. }
  704. }
  705. }
  706. if (auto const* prototype = shape.prototype()) {
  707. list_all_properties(prototype->shape(), property_pattern);
  708. }
  709. };
  710. switch (mode) {
  711. case CompleteProperty: {
  712. auto reference_or_error = g_vm->resolve_binding(variable_name, &global_environment);
  713. if (reference_or_error.is_error())
  714. return {};
  715. auto value_or_error = reference_or_error.value().get_value(*g_vm);
  716. if (value_or_error.is_error())
  717. return {};
  718. auto variable = value_or_error.value();
  719. VERIFY(!variable.is_empty());
  720. if (!variable.is_object())
  721. break;
  722. auto const* object = MUST(variable.to_object(*g_vm));
  723. auto const& shape = object->shape();
  724. list_all_properties(shape, property_name);
  725. break;
  726. }
  727. case CompleteVariable: {
  728. auto const& variable = interpreter->realm().global_object();
  729. list_all_properties(variable.shape(), variable_name);
  730. for (auto const& name : global_environment.declarative_record().bindings()) {
  731. if (name.starts_with(variable_name)) {
  732. results.empend(name);
  733. results.last().invariant_offset = variable_name.length();
  734. }
  735. }
  736. break;
  737. }
  738. default:
  739. VERIFY_NOT_REACHED();
  740. }
  741. return results;
  742. };
  743. s_editor->on_tab_complete = move(complete);
  744. TRY(repl(*interpreter));
  745. s_editor->save_history(s_history_path);
  746. } else {
  747. interpreter = JS::Interpreter::create<ScriptObject>(*g_vm);
  748. auto& console_object = *interpreter->realm().intrinsics().console_object();
  749. ReplConsoleClient console_client(console_object.console());
  750. console_object.console().set_client(console_client);
  751. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  752. signal(SIGINT, [](int) {
  753. sigint_handler();
  754. });
  755. StringBuilder builder;
  756. StringView source_name;
  757. if (evaluate_script.is_empty()) {
  758. if (script_paths.size() > 1)
  759. warnln("Warning: Multiple files supplied, this will concatenate the sources and resolve modules as if it was the first file");
  760. for (auto& path : script_paths) {
  761. auto file = TRY(Core::Stream::File::open(path, Core::Stream::OpenMode::Read));
  762. auto file_contents = TRY(file->read_all());
  763. auto source = StringView { file_contents };
  764. if (Utf8View { file_contents }.validate()) {
  765. builder.append(source);
  766. } else {
  767. auto* decoder = TextCodec::decoder_for("windows-1252");
  768. VERIFY(decoder);
  769. auto utf8_source = TextCodec::convert_input_to_utf8_using_given_decoder_unless_there_is_a_byte_order_mark(*decoder, source);
  770. builder.append(utf8_source);
  771. }
  772. }
  773. source_name = script_paths[0];
  774. } else {
  775. builder.append(evaluate_script);
  776. source_name = "eval"sv;
  777. }
  778. // We resolve modules as if it is the first file
  779. if (!TRY(parse_and_run(*interpreter, builder.string_view(), source_name)))
  780. return 1;
  781. }
  782. return 0;
  783. }