js.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  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<DeprecatedString> 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 JS::ThrowCompletionOr<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 JS::ThrowCompletionOr<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 DeprecatedString s_history_path = DeprecatedString::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, AK::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 ErrorOr<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.to_string();
  99. }
  100. static ErrorOr<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(TRY(prompt_for_level(s_repl_line_level)).to_deprecated_string());
  106. line_level_delta_for_next_line = 0;
  107. if (line_result.is_error()) {
  108. s_fail_repl = true;
  109. return String {};
  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(DeprecatedString 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_deprecated_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_deprecated_string());
  233. result = interpreter.vm().throw_completion<JS::SyntaxError>(error.to_deprecated_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_deprecated_string());
  247. result = interpreter.vm().throw_completion<JS::SyntaxError>(error.to_deprecated_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_deprecated_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>(DeprecatedString::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::PrimitiveString::create(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_deprecated_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>(DeprecatedString::formatted("Failed to open '{}': {}", filename, file_or_error.error()));
  325. auto file_contents_or_error = file_or_error.value()->read_until_eof();
  326. if (file_contents_or_error.is_error())
  327. return vm.throw_completion<JS::Error>(DeprecatedString::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. JS::ThrowCompletionOr<void> ReplObject::initialize(JS::Realm& realm)
  334. {
  335. MUST_OR_THROW_OOM(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. return {};
  362. }
  363. JS_DEFINE_NATIVE_FUNCTION(ReplObject::save_to_file)
  364. {
  365. if (!vm.argument_count())
  366. return JS::Value(false);
  367. DeprecatedString save_path = vm.argument(0).to_string_without_side_effects();
  368. if (write_to_file(save_path)) {
  369. return JS::Value(true);
  370. }
  371. return JS::Value(false);
  372. }
  373. JS_DEFINE_NATIVE_FUNCTION(ReplObject::exit_interpreter)
  374. {
  375. if (!vm.argument_count())
  376. exit(0);
  377. exit(TRY(vm.argument(0).to_number(vm)).as_double());
  378. }
  379. JS_DEFINE_NATIVE_FUNCTION(ReplObject::repl_help)
  380. {
  381. warnln("REPL commands:");
  382. warnln(" exit(code): exit the REPL with specified code. Defaults to 0.");
  383. warnln(" help(): display this menu");
  384. warnln(" loadINI(file): load the given file as INI.");
  385. warnln(" loadJSON(file): load the given file as JSON.");
  386. warnln(" print(value): pretty-print the given JS value.");
  387. warnln(" save(file): write REPL input history to the given file. For example: save(\"foo.txt\")");
  388. return JS::js_undefined();
  389. }
  390. JS_DEFINE_NATIVE_FUNCTION(ReplObject::load_ini)
  391. {
  392. return load_ini_impl(vm);
  393. }
  394. JS_DEFINE_NATIVE_FUNCTION(ReplObject::load_json)
  395. {
  396. return load_json_impl(vm);
  397. }
  398. JS_DEFINE_NATIVE_FUNCTION(ReplObject::print)
  399. {
  400. auto result = ::print(vm.argument(0));
  401. if (result.is_error())
  402. return g_vm->throw_completion<JS::InternalError>(DeprecatedString::formatted("Failed to print value: {}", result.error()));
  403. outln();
  404. return JS::js_undefined();
  405. }
  406. JS::ThrowCompletionOr<void> ScriptObject::initialize(JS::Realm& realm)
  407. {
  408. MUST_OR_THROW_OOM(Base::initialize(realm));
  409. define_direct_property("global", this, JS::Attribute::Enumerable);
  410. u8 attr = JS::Attribute::Configurable | JS::Attribute::Writable | JS::Attribute::Enumerable;
  411. define_native_function(realm, "loadINI", load_ini, 1, attr);
  412. define_native_function(realm, "loadJSON", load_json, 1, attr);
  413. define_native_function(realm, "print", print, 1, attr);
  414. return {};
  415. }
  416. JS_DEFINE_NATIVE_FUNCTION(ScriptObject::load_ini)
  417. {
  418. return load_ini_impl(vm);
  419. }
  420. JS_DEFINE_NATIVE_FUNCTION(ScriptObject::load_json)
  421. {
  422. return load_json_impl(vm);
  423. }
  424. JS_DEFINE_NATIVE_FUNCTION(ScriptObject::print)
  425. {
  426. auto result = ::print(vm.argument(0));
  427. if (result.is_error())
  428. return g_vm->throw_completion<JS::InternalError>(DeprecatedString::formatted("Failed to print value: {}", result.error()));
  429. outln();
  430. return JS::js_undefined();
  431. }
  432. static ErrorOr<void> repl(JS::Interpreter& interpreter)
  433. {
  434. while (!s_fail_repl) {
  435. auto const piece = TRY(read_next_piece());
  436. if (Utf8View { piece }.trim(JS::whitespace_characters).is_empty())
  437. continue;
  438. g_repl_statements.append(piece.to_deprecated_string());
  439. TRY(parse_and_run(interpreter, piece, "REPL"sv));
  440. }
  441. return {};
  442. }
  443. static Function<void()> interrupt_interpreter;
  444. static void sigint_handler()
  445. {
  446. interrupt_interpreter();
  447. }
  448. class ReplConsoleClient final : public JS::ConsoleClient {
  449. public:
  450. ReplConsoleClient(JS::Console& console)
  451. : ConsoleClient(console)
  452. {
  453. }
  454. virtual void clear() override
  455. {
  456. out("\033[3J\033[H\033[2J");
  457. m_group_stack_depth = 0;
  458. fflush(stdout);
  459. }
  460. virtual void end_group() override
  461. {
  462. if (m_group_stack_depth > 0)
  463. m_group_stack_depth--;
  464. }
  465. // 2.3. Printer(logLevel, args[, options]), https://console.spec.whatwg.org/#printer
  466. virtual JS::ThrowCompletionOr<JS::Value> printer(JS::Console::LogLevel log_level, PrinterArguments arguments) override
  467. {
  468. DeprecatedString indent = DeprecatedString::repeated(" "sv, m_group_stack_depth);
  469. if (log_level == JS::Console::LogLevel::Trace) {
  470. auto trace = arguments.get<JS::Console::Trace>();
  471. StringBuilder builder;
  472. if (!trace.label.is_empty())
  473. builder.appendff("{}\033[36;1m{}\033[0m\n", indent, trace.label);
  474. for (auto& function_name : trace.stack)
  475. builder.appendff("{}-> {}\n", indent, function_name);
  476. outln("{}", builder.string_view());
  477. return JS::js_undefined();
  478. }
  479. if (log_level == JS::Console::LogLevel::Group || log_level == JS::Console::LogLevel::GroupCollapsed) {
  480. auto group = arguments.get<JS::Console::Group>();
  481. outln("{}\033[36;1m{}\033[0m", indent, group.label);
  482. m_group_stack_depth++;
  483. return JS::js_undefined();
  484. }
  485. auto output = DeprecatedString::join(' ', arguments.get<JS::MarkedVector<JS::Value>>());
  486. #ifdef AK_OS_SERENITY
  487. m_console.output_debug_message(log_level, output);
  488. #endif
  489. switch (log_level) {
  490. case JS::Console::LogLevel::Debug:
  491. outln("{}\033[36;1m{}\033[0m", indent, output);
  492. break;
  493. case JS::Console::LogLevel::Error:
  494. case JS::Console::LogLevel::Assert:
  495. outln("{}\033[31;1m{}\033[0m", indent, output);
  496. break;
  497. case JS::Console::LogLevel::Info:
  498. outln("{}(i) {}", indent, output);
  499. break;
  500. case JS::Console::LogLevel::Log:
  501. outln("{}{}", indent, output);
  502. break;
  503. case JS::Console::LogLevel::Warn:
  504. case JS::Console::LogLevel::CountReset:
  505. outln("{}\033[33;1m{}\033[0m", indent, output);
  506. break;
  507. default:
  508. outln("{}{}", indent, output);
  509. break;
  510. }
  511. return JS::js_undefined();
  512. }
  513. private:
  514. int m_group_stack_depth { 0 };
  515. };
  516. ErrorOr<int> serenity_main(Main::Arguments arguments)
  517. {
  518. TRY(Core::System::pledge("stdio rpath wpath cpath tty sigaction"));
  519. bool gc_on_every_allocation = false;
  520. bool disable_syntax_highlight = false;
  521. StringView evaluate_script;
  522. Vector<StringView> script_paths;
  523. Core::ArgsParser args_parser;
  524. args_parser.set_general_help("This is a JavaScript interpreter.");
  525. args_parser.add_option(s_dump_ast, "Dump the AST", "dump-ast", 'A');
  526. args_parser.add_option(JS::Bytecode::g_dump_bytecode, "Dump the bytecode", "dump-bytecode", 'd');
  527. args_parser.add_option(s_run_bytecode, "Run the bytecode", "run-bytecode", 'b');
  528. args_parser.add_option(s_opt_bytecode, "Optimize the bytecode", "optimize-bytecode", 'p');
  529. args_parser.add_option(s_as_module, "Treat as module", "as-module", 'm');
  530. args_parser.add_option(s_print_last_result, "Print last result", "print-last-result", 'l');
  531. args_parser.add_option(s_strip_ansi, "Disable ANSI colors", "disable-ansi-colors", 'i');
  532. args_parser.add_option(s_disable_source_location_hints, "Disable source location hints", "disable-source-location-hints", 'h');
  533. args_parser.add_option(gc_on_every_allocation, "GC on every allocation", "gc-on-every-allocation", 'g');
  534. args_parser.add_option(disable_syntax_highlight, "Disable live syntax highlighting", "no-syntax-highlight", 's');
  535. args_parser.add_option(evaluate_script, "Evaluate argument as a script", "evaluate", 'c', "script");
  536. args_parser.add_positional_argument(script_paths, "Path to script files", "scripts", Core::ArgsParser::Required::No);
  537. args_parser.parse(arguments);
  538. bool syntax_highlight = !disable_syntax_highlight;
  539. g_vm = JS::VM::create();
  540. g_vm->enable_default_host_import_module_dynamically_hook();
  541. // NOTE: These will print out both warnings when using something like Promise.reject().catch(...) -
  542. // which is, as far as I can tell, correct - a promise is created, rejected without handler, and a
  543. // handler then attached to it. The Node.js REPL doesn't warn in this case, so it's something we
  544. // might want to revisit at a later point and disable warnings for promises created this way.
  545. g_vm->on_promise_unhandled_rejection = [](auto& promise) {
  546. warn("WARNING: A promise was rejected without any handlers");
  547. warn(" (result: ");
  548. (void)print(promise.result(), PrintTarget::StandardError);
  549. warnln(")");
  550. };
  551. g_vm->on_promise_rejection_handled = [](auto& promise) {
  552. warn("WARNING: A handler was added to an already rejected promise");
  553. warn(" (result: ");
  554. (void)print(promise.result(), PrintTarget::StandardError);
  555. warnln(")");
  556. };
  557. OwnPtr<JS::Interpreter> interpreter;
  558. // FIXME: Figure out some way to interrupt the interpreter now that vm.exception() is gone.
  559. if (evaluate_script.is_empty() && script_paths.is_empty()) {
  560. s_print_last_result = true;
  561. interpreter = JS::Interpreter::create<ReplObject>(*g_vm);
  562. auto& console_object = *interpreter->realm().intrinsics().console_object();
  563. ReplConsoleClient console_client(console_object.console());
  564. console_object.console().set_client(console_client);
  565. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  566. auto& global_environment = interpreter->realm().global_environment();
  567. s_editor = Line::Editor::construct();
  568. s_editor->load_history(s_history_path);
  569. signal(SIGINT, [](int) {
  570. if (!s_editor->is_editing())
  571. sigint_handler();
  572. s_editor->save_history(s_history_path);
  573. });
  574. s_editor->on_display_refresh = [syntax_highlight](Line::Editor& editor) {
  575. auto stylize = [&](Line::Span span, Line::Style styles) {
  576. if (syntax_highlight)
  577. editor.stylize(span, styles);
  578. };
  579. editor.strip_styles();
  580. size_t open_indents = s_repl_line_level;
  581. auto line = editor.line();
  582. JS::Lexer lexer(line);
  583. bool indenters_starting_line = true;
  584. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  585. auto length = Utf8View { token.value() }.length();
  586. auto start = token.offset();
  587. auto end = start + length;
  588. if (indenters_starting_line) {
  589. if (token.type() != JS::TokenType::ParenClose && token.type() != JS::TokenType::BracketClose && token.type() != JS::TokenType::CurlyClose) {
  590. indenters_starting_line = false;
  591. } else {
  592. --open_indents;
  593. }
  594. }
  595. switch (token.category()) {
  596. case JS::TokenCategory::Invalid:
  597. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Red), Line::Style::Underline });
  598. break;
  599. case JS::TokenCategory::Number:
  600. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Magenta) });
  601. break;
  602. case JS::TokenCategory::String:
  603. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Green), Line::Style::Bold });
  604. break;
  605. case JS::TokenCategory::Punctuation:
  606. break;
  607. case JS::TokenCategory::Operator:
  608. break;
  609. case JS::TokenCategory::Keyword:
  610. switch (token.type()) {
  611. case JS::TokenType::BoolLiteral:
  612. case JS::TokenType::NullLiteral:
  613. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow), Line::Style::Bold });
  614. break;
  615. default:
  616. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Blue), Line::Style::Bold });
  617. break;
  618. }
  619. break;
  620. case JS::TokenCategory::ControlKeyword:
  621. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan), Line::Style::Italic });
  622. break;
  623. case JS::TokenCategory::Identifier:
  624. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::White), Line::Style::Bold });
  625. break;
  626. default:
  627. break;
  628. }
  629. }
  630. editor.set_prompt(prompt_for_level(open_indents).release_value_but_fixme_should_propagate_errors().to_deprecated_string());
  631. };
  632. auto complete = [&interpreter, &global_environment](Line::Editor const& editor) -> Vector<Line::CompletionSuggestion> {
  633. auto line = editor.line(editor.cursor());
  634. JS::Lexer lexer { line };
  635. enum {
  636. Initial,
  637. CompleteVariable,
  638. CompleteNullProperty,
  639. CompleteProperty,
  640. } mode { Initial };
  641. StringView variable_name;
  642. StringView property_name;
  643. // we're only going to complete either
  644. // - <N>
  645. // where N is part of the name of a variable
  646. // - <N>.<P>
  647. // where N is the complete name of a variable and
  648. // P is part of the name of one of its properties
  649. auto js_token = lexer.next();
  650. for (; js_token.type() != JS::TokenType::Eof; js_token = lexer.next()) {
  651. switch (mode) {
  652. case CompleteVariable:
  653. switch (js_token.type()) {
  654. case JS::TokenType::Period:
  655. // ...<name> <dot>
  656. mode = CompleteNullProperty;
  657. break;
  658. default:
  659. // not a dot, reset back to initial
  660. mode = Initial;
  661. break;
  662. }
  663. break;
  664. case CompleteNullProperty:
  665. if (js_token.is_identifier_name()) {
  666. // ...<name> <dot> <name>
  667. mode = CompleteProperty;
  668. property_name = js_token.value();
  669. } else {
  670. mode = Initial;
  671. }
  672. break;
  673. case CompleteProperty:
  674. // something came after the property access, reset to initial
  675. case Initial:
  676. if (js_token.type() == JS::TokenType::Identifier) {
  677. // ...<name>...
  678. mode = CompleteVariable;
  679. variable_name = js_token.value();
  680. } else {
  681. mode = Initial;
  682. }
  683. break;
  684. }
  685. }
  686. bool last_token_has_trivia = js_token.trivia().length() > 0;
  687. if (mode == CompleteNullProperty) {
  688. mode = CompleteProperty;
  689. property_name = ""sv;
  690. last_token_has_trivia = false; // <name> <dot> [tab] is sensible to complete.
  691. }
  692. if (mode == Initial || last_token_has_trivia)
  693. return {}; // we do not know how to complete this
  694. Vector<Line::CompletionSuggestion> results;
  695. Function<void(JS::Shape const&, StringView)> list_all_properties = [&results, &list_all_properties](JS::Shape const& shape, auto property_pattern) {
  696. for (auto const& descriptor : shape.property_table()) {
  697. if (!descriptor.key.is_string())
  698. continue;
  699. auto key = descriptor.key.as_string();
  700. if (key.view().starts_with(property_pattern)) {
  701. Line::CompletionSuggestion completion { key, Line::CompletionSuggestion::ForSearch };
  702. if (!results.contains_slow(completion)) { // hide duplicates
  703. results.append(DeprecatedString(key));
  704. results.last().invariant_offset = property_pattern.length();
  705. }
  706. }
  707. }
  708. if (auto const* prototype = shape.prototype()) {
  709. list_all_properties(prototype->shape(), property_pattern);
  710. }
  711. };
  712. switch (mode) {
  713. case CompleteProperty: {
  714. auto reference_or_error = g_vm->resolve_binding(variable_name, &global_environment);
  715. if (reference_or_error.is_error())
  716. return {};
  717. auto value_or_error = reference_or_error.value().get_value(*g_vm);
  718. if (value_or_error.is_error())
  719. return {};
  720. auto variable = value_or_error.value();
  721. VERIFY(!variable.is_empty());
  722. if (!variable.is_object())
  723. break;
  724. auto const* object = MUST(variable.to_object(*g_vm));
  725. auto const& shape = object->shape();
  726. list_all_properties(shape, property_name);
  727. break;
  728. }
  729. case CompleteVariable: {
  730. auto const& variable = interpreter->realm().global_object();
  731. list_all_properties(variable.shape(), variable_name);
  732. for (auto const& name : global_environment.declarative_record().bindings()) {
  733. if (name.starts_with(variable_name)) {
  734. results.empend(name);
  735. results.last().invariant_offset = variable_name.length();
  736. }
  737. }
  738. break;
  739. }
  740. default:
  741. VERIFY_NOT_REACHED();
  742. }
  743. return results;
  744. };
  745. s_editor->on_tab_complete = move(complete);
  746. TRY(repl(*interpreter));
  747. s_editor->save_history(s_history_path);
  748. } else {
  749. interpreter = JS::Interpreter::create<ScriptObject>(*g_vm);
  750. auto& console_object = *interpreter->realm().intrinsics().console_object();
  751. ReplConsoleClient console_client(console_object.console());
  752. console_object.console().set_client(console_client);
  753. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  754. signal(SIGINT, [](int) {
  755. sigint_handler();
  756. });
  757. StringBuilder builder;
  758. StringView source_name;
  759. if (evaluate_script.is_empty()) {
  760. if (script_paths.size() > 1)
  761. warnln("Warning: Multiple files supplied, this will concatenate the sources and resolve modules as if it was the first file");
  762. for (auto& path : script_paths) {
  763. auto file = TRY(Core::Stream::File::open(path, Core::Stream::OpenMode::Read));
  764. auto file_contents = TRY(file->read_until_eof());
  765. auto source = StringView { file_contents };
  766. if (Utf8View { file_contents }.validate()) {
  767. builder.append(source);
  768. } else {
  769. auto* decoder = TextCodec::decoder_for("windows-1252");
  770. VERIFY(decoder);
  771. auto utf8_source = TextCodec::convert_input_to_utf8_using_given_decoder_unless_there_is_a_byte_order_mark(*decoder, source);
  772. builder.append(utf8_source);
  773. }
  774. }
  775. source_name = script_paths[0];
  776. } else {
  777. builder.append(evaluate_script);
  778. source_name = "eval"sv;
  779. }
  780. // We resolve modules as if it is the first file
  781. if (!TRY(parse_and_run(*interpreter, builder.string_view(), source_name)))
  782. return 1;
  783. }
  784. return 0;
  785. }