js.cpp 35 KB

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